Matt Cremeens
Matt Cremeens

Reputation: 5151

Use plotly offline to generate graphs as images

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?

Upvotes: 17

Views: 47968

Answers (5)

Shantanu Deshmukh
Shantanu Deshmukh

Reputation: 545

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!

Upvotes: 3

LordK
LordK

Reputation: 161

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

Upvotes: 15

RFQED
RFQED

Reputation: 27

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')

Upvotes: -2

Benares
Benares

Reputation: 1288

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')

Upvotes: 9

Benares
Benares

Reputation: 1288

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

Upvotes: 0

Related Questions