Skip to content

Instantly share code, notes, and snippets.

@kstohr
Last active April 13, 2017 05:00
Show Gist options
  • Save kstohr/b9392467a0d99a1e3f2b23e2fc4efe3f to your computer and use it in GitHub Desktop.
Save kstohr/b9392467a0d99a1e3f2b23e2fc4efe3f to your computer and use it in GitHub Desktop.
How to uses plot.ly to plot inline and save files to imbed on web pages
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.graph_objs import *
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
import plotly.tools as tls
from IPython.display import HTML
#Set options
pd.set_option('display.max_colwidth', -1)
#set inline plotting
%matplotlib inline
plotly.offline.init_notebook_mode()
#plot matplot plots with plotly
mpl_fig_obj = plt.figure()
#Plot.ly api credentials
PLOTLY_USER = os.environ['PLOTLY_USER']
PLOTLY_KEY = os.environ['PLOTLY_KEY']
py.sign_in(PLOTLY_USER, PLOTLY_KEY)
#Get data
#Source data: https://docs.google.com/spreadsheets/d/1YcoFv_ht59v1fxGK_mInUX8Qkq60t-yTSLbvPNdy6OY/pub?output=csv
URL="https://docs.google.com/spreadsheets/d/1YcoFv_ht59v1fxGK_mInUX8Qkq60t-yTSLbvPNdy6OY/pub?output=csv"
data = pd.read_csv(URL, index_col = 'Unnamed: 0', dtype = object, encoding = 'utf-8')
#Sort data
trump_p = data.sort_values(by = 'category')
#Sample plot: Facebook Pages Related to Donald Trump's Presidential Campaign (as of April 2016)
positions = ['Pro', 'Con', 'Commercial']
py.iplot({
'data': [
Scatter(x=trump_p[trump_p['category']== position]['likes'],
y=trump_p[trump_p['category']== position]['talking_about_count'],
text=trump_p[trump_p['category']== position]['name'],
marker=Marker(size=trump_p[trump_p['category']== position]['likes'],
sizemode='area',
sizeref = trump_p['likes'].max()/ 1e2**1.75),
mode='markers',
name=position
) for position in positions
],
'layout': Layout(title = "Facebook Pages Related to Donald Trump's Campaign",
xaxis=XAxis(title='Number of Likes',
#autorange=False,
#range=[-104000, 708000]
),
yaxis=YAxis(title= "Talking About Count",
showticklabels = True,
#autorange=False,
#range=[0, 900000]
),
width = 600)
}, filename='facebook_groups/bubble-trump-pages')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment