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?
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
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')
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!
one possibility using ipython notebook is to display the graph and then choose the option "Download plot as png" manually.
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')
Related
I've got a simple plotly line graph:
import plotly.express as px
fig = px.line(data, x="x-axis", y="variable")
fig.show()
I want to add data labels displaying each y-axis value to each point, but I can't work out how to do it using the plotly api. Is it possible? Can anyone point out how?
have simulated dataframe for your figure
two steps
define text parameter so trace / figure is built appropriately by Plotly Express
updated texttemplate so that formatting of y-axis is used
import plotly.express as px
import pandas as pd
import numpy as np
data = pd.DataFrame(
{
"x-axis": np.arange(0, 12),
"variable": (np.cos(np.linspace(np.pi / 2, np.pi, 12)) + 1) / 25,
}
)
fig = px.line(data, x="x-axis", y="variable", text="variable")
fig.update_traces(texttemplate="%{y}")
fig.update_layout(yaxis_tickformat=".2%")
tried the example in an earlier question but I cannot get it to "render" properly:
# imports
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
# data
df = pd.DataFrame({'BA': ['BA1', 'BA2', 'BA3', 'BA4','BA2'],
'RS': [12, 13,15, 20, 18],
'RC': ['medium','medium', 'high','high','high'] })
# plotly express figure
fig = px.sunburst(df, path=["BA", "RC"])
fig.show()
# plotly graph_objects figure
fig2=go.Figure(go.Sunburst(
labels=fig['data'][0]['labels'].tolist(),
parents=fig['data'][0]['parents'].tolist(),
)
)
fig2.show()
results in:
enter image description here
enter image description here
What am I doing wrong? (i expected it to look like the first picture).. using conda + jupyter lab
If you take a look at fig['data'], you will see that there is a field called ids which tells Plotly how to connect the parents to the labels. You need to specify this as a parameter as well.
EDIT: if you want to display values the same way as px.sunburst, you also need to include the parameter branchvalues='total'
# plotly graph_objects figure
fig2=go.Figure(go.Sunburst(
branchvalues='total',
ids=fig['data'][0]['ids'].tolist(),
labels=fig['data'][0]['labels'].tolist(),
parents=fig['data'][0]['parents'].tolist(),
values=fig['data'][0]['values'].tolist()
)
)
fig2.show()
I have a huge problem with Jupyter Notebook.
When he builds graphs using the plot packet, to display the next graph I have to reload the dataset, otherwise an error pops up: TypeError: list indices must be integers or slices, not str. When I reopen the project, all the graphs created using Plotly are not visible, just a white background and I have to reload them if I want to see them, and everything after reloading the dataset, that is:
1) I open the project in Jupyte Notebook, all graphs created by Plotly are not visible (others from Seaborn for example are visible.
2) I load the Plotly charts, but I can load them one by one, because first I have to load the dataset, then the chart, and so an error occurs to all Plotly charts differently: TypeError: list indices must be integers or slices
what can I do about it how to fix it? it seriously hinders the work
this is my libraries:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import plotly.offline as py
import plotly.graph_objs as go
import plotly.tools as tls
This is an example of this error, but if I load the dataset again and again load this plot everything will be ok:
and the example of the code of plot:
#Distribution of credit risk in dataset (target variable)
#Size of the plot
figsize=(10,5)
#Sums of good and bad credits in the dataset
goodCount = data[data["Risk"]== 'good']["Risk"].value_counts().values
badCount = data[data["Risk"]== 'bad']["Risk"].value_counts().values
#Bar fo good credit
trace0 = go.Bar(x = data[data["Risk"]== 'good']["Risk"].value_counts().index.values,
y = data[data["Risk"]== 'good']["Risk"].value_counts().values,
name='Good credit',
text= goodCount,
textposition="auto",
marker = dict(color = "green", line=dict(color="black", width=1),),opacity=1)
#Bar of bad credit
trace1 = go.Bar(x = data[data["Risk"]== 'bad']["Risk"].value_counts().index.values,
y = data[data["Risk"]== 'bad']["Risk"].value_counts().values,
name='Bad credit',
text= badCount,
textposition="auto",
marker = dict(color = "red", line=dict(color="black", width=1),),opacity=1)
#Creation of bar plot
data = [trace0, trace1]
layout = go.Layout()
layout = go.Layout(yaxis=dict(title='Count'),
xaxis=dict(title='Risk variable'),
title='Distribution of target variable in the dataset')
fig = go.Figure(data=data, layout=layout)
fig.show()
How to export/save an animated bubble chart made with plotly? (For instance, the one was made following the link below) I would like to have it in a gift or some format with better resolution. Thank you in advance.
https://www.kaggle.com/aashita/guide-to-animated-bubble-charts-using-plotly
There is no possibility to do this in plotly. Please use gifmaker and save every step in the animation as a single picture to later combine them to a gif. Follow this source. Further explanation on how to create animations is provided by plotly here.
The basic way to go would be to integrate this logic into the animation process of your plotly code:
import ImageSequence
import Image
import gifmaker
sequence = []
im = Image.open(....)
# im is your original image
frames = [frame.copy() for frame in ImageSequence.Iterator(im)]
# write GIF animation
fp = open("out.gif", "wb")
gifmaker.makedelta(fp, frames)
fp.close()
If you could provide your actual code, it would be possible to provide a more detailled answer to your question. :)
Another possibility is to use the gif library, which works with matplolib, altair and plotly, and is really straight forward. In this case you would not use a plotly animation. Instead, you define a function that returns a plotly fig and construct a list of figs to pass to gif as an argument.
Your code would look something like this:
import random
import plotly.graph_objects as go
import pandas as pd
import gif
# Pandas DataFrame with random data
df = pd.DataFrame({
't': list(range(10)) * 10,
'x': [random.randint(0, 100) for _ in range(100)],
'y': [random.randint(0, 100) for _ in range(100)]
})
# Gif function definition
#gif.frame
def plot(i):
d = df[df['t'] == i]
fig = go.Figure()
fig.add_trace(go.Scatter(
x=d["x"],
y=d["y"],
mode="markers"
))
fig.update_layout(width=500, height=300)
return fig
# Construct list of frames
frames = []
for i in range(10):
frame = plot(i)
frames.append(frame)
# Save gif from frames with a specific duration for each frame in ms
gif.save(frames, 'example.gif', duration=100)
Building on answers already provided. This generates an animated GIF from an plotly figure that has frames (is animated)
start by generating some test data
generate an animated figure using plotly express
create an image for each frame in plotly figure
finally generate animated GIF from list of images
import plotly.express as px
import pandas as pd
import numpy as np
import io
import PIL
r = np.random.RandomState(42)
# sample data
df = pd.DataFrame(
{
"step": np.repeat(np.arange(0, 8), 10),
"x": np.tile(np.linspace(0, 9, 10), 8),
"y": r.uniform(0, 5, 80),
}
)
# smaple plotly animated figure
fig = px.bar(df, x="x", y="y", animation_frame="step")
# generate images for each step in animation
frames = []
for s, fr in enumerate(fig.frames):
# set main traces to appropriate traces within plotly frame
fig.update(data=fr.data)
# move slider to correct place
fig.layout.sliders[0].update(active=s)
# generate image of current state
frames.append(PIL.Image.open(io.BytesIO(fig.to_image(format="png"))))
# create animated GIF
frames[0].save(
"test.gif",
save_all=True,
append_images=frames[1:],
optimize=True,
duration=500,
loop=0,
)
I was trying to plot choropleth map using plotly but getting a blank output.I am not getting any map.here is my code-
input-
import plotly.plotly as py
from plotly.offline import download_plotlyjs,init_notebook_mode,plot,iplot
import plotly.graph_objs as go
init_notebook_mode(connected=True)
%matplotlib inline
data = dict(type = 'choropleth',
locations = ['AZ','CA','NY'],
locationmode = 'USA-states',
colorscale= 'Portland',
text= ['text1','text2','text3'],
z=[1.0,2.0,3.0],
colorbar = {'title':'Colorbar Title'})
layout = dict(geo = {'scope':'usa'})
choromap = go.Figure(data=[data] , layout=layout)
iplot(choromap )
output-
it is a blank screen. I am sharing my screenshot.What is the issue?
Thank you in advance
https://drive.google.com/file/d/14R6zfNxnefBoe3RFlFH2YunlTbrFzfRX/view?usp=sharing
Just double click on the white space and you will get the desired output.
This worked for me.
Thanks