Use plotly offline to generate graphs as images

和自甴很熟 提交于 2019-12-04 09:15:47

问题


I am working with plotly offline and am able to generate an html file using

plotly.offline.plot({"data": data, "layout": layout})

It works great. The graph is generated correctly and the html file gets saved to my current directory.

What I want, though is, using plotly offline, is to have an image (.png, .jpg, etc.) file saved instead. Am I on the right track? What do I need to do from here?


回答1:


Try this

import plotly.offline
import plotly.graph_objs as go

plotly.offline.plot({"data": [go.Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
                     "layout": go.Layout(title="hello world")},
                     image='jpeg', image_filename='test')

and open it in Chrome




回答2:


I found the solution in the documentation here:

https://plot.ly/python/static-image-export/

So a minimal example would be:

import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np

N = 1000
random_x = np.random.randn(N)
random_y = np.random.randn(N)

trace = go.Scatter(
    x = random_x,
    y = random_y,
    mode = 'markers'
)

data = [trace]

py.image.save_as({'data':data}, 'scatter_plot', format='png')



回答3:


one possibility using ipython notebook is to display the graph and then choose the option "Download plot as png" manually.




回答4:


Simple way of using python plotly graphs offline:

1) Write import statements

import plotly.graph_objs as go
import plotly as plotly
import plotly.express as px

2) write your plotly graph code e.g.

data = px.data.gapminder()

data_canada = data[data.country == 'Canada']
fig = px.bar(data_canada, x='year', y='pop',
             hover_data=['lifeExp', 'gdpPercap'], color='lifeExp',
             labels={'pop':'population of Canada'}, height=400)

3) name your figure (provide reader-friendly name :) )

plotly.offline.plot(fig, filename= output_filename + ".html")

4) Well-done! Please add comments, if you like my answer!




回答5:


Here says to use

import plotly.plotly as py
# Generate the figure

trace = Bar(x=[1,2,3],y=[4,5,6])
data = [trace]
layout = Layout(title='My Plot')
fig = Figure(data=data,layout=layout)

# Save the figure as a png image:
py.image.save_as(fig, 'my_plot.png')


来源:https://stackoverflow.com/questions/34957790/use-plotly-offline-to-generate-graphs-as-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!