Created
November 18, 2015 02:28
-
-
Save ghl3/e43a3862e4d9d7d9db31 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
from plotly import __version__ | |
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot | |
from plotly import tools, utils | |
from plotly.graph_objs import Scatter, Marker, Layout, XAxis, YAxis | |
def get_json_for_js(data): | |
figure = tools.return_figure_from_figure_or_data(data, True) | |
fig = tools._replace_newline(figure) # does not mutate figure | |
d = json.dumps(fig['data'] if 'data' in fig else [], | |
cls=utils.PlotlyJSONEncoder) | |
l = fig['layout'] if 'layout' in fig else {} | |
return (d, json.dumps(l)) | |
def get_plotly_html(data): | |
d, l = get_json_for_js(data) | |
html = """<html> | |
<head> | |
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script> | |
</head> | |
<body> | |
<div id="foobar"></div> | |
<script> | |
var data = %s; | |
var layout = %s; | |
Plotly.plot('foobar', data, layout, {showLink: false}); | |
</script> | |
</body> | |
</html>""" % (d, l) | |
return html | |
python_data = { | |
'data': [ | |
Scatter(x=df[continent+'_Life Expentancy [in years]'], | |
y=df[continent+'_Gross Domestic Product per Capita [in USD of the year 2000]'], | |
text=df[continent+'_text'], | |
marker=Marker(size=df[continent+'_marker.size'], sizemode='area', sizeref=131868,), | |
mode='markers', | |
name=continent) for continent in ['Africa', 'Americas', 'Asia', 'Europe', 'Oceania'] | |
], | |
'layout': Layout(xaxis=XAxis(title='Life Expectancy'), yaxis=YAxis(title='GDP per Capita', type='log')) | |
} | |
with open('plotly.html', 'w+') as f: | |
f.write(get_plotly_html(python_data)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice! Would love to see this incorporated into the library. I've reserved
plotly.offline.plot
: https://github.com/plotly/plotly.py/blob/master/plotly/offline/offline.py#L171-L174 for this type of behaviour :)