Animated multiseries Line Graph using Plotly Express (Python) - python

I am trying to animate a multi series line graph using plotly. However after days of going through the documentation I still can't seem to find a solution.
Currently my code is as follows:
df = px.data.gapminder().query("continent=='Oceania' ")
fig = px.line(df, x="year" , y="lifeExp", color="country" , animation_frame="year", animation_group="lifeExp" , range_y=[68,84] , range_x=[1950,2010])
plot(fig)
This however generates and empty plot. Please help.
I am able to successfully generate a scatter plot and a bar graph using similar code.
For better understanding please view below link :
I have found an exact example of what I am looking for implemented in R.
https://plot.ly/r/cumulative-animations/#cumulative-lines-animation

For the empty plot, try changing the default renderer by adding this above your code:
import plotly.io as pio
pio.renderers.default = 'notebook'
There is some documentation on different renderers.

Related

Can't get map to appear in Python Data Visualization

I am trying to visualize US COVID-19 data geographically within Python. Currently I have a CSV with all my data imported which contains case numbers, longitudes, latitudes etc. Currently my code is as follows:
df=pd.read_csv
fig=px.scatter_mapbox(df,lat='Lat', lon='Long', hover_name='Province_State', size='Confirmed',mapbox_style='open-streetmap',template='plotly_dark')
fig.write_html("Time_series_county_JH.html")
fig.show()
However, when I run the code I just get a black box with the legend on the right
Would be great if someone can help on how I can get the actual map to appear rather than just a black output. I am very new to Python so any help would be greatly appreciated.
I think you are facing a problem with rendering the image using plotly.
You could set the renderers for the plotly image as below:
import plotly.io as pio
pio.renderers.default = "colab"
And change the following line in your code as shown below:
pio.show(fig)
If the figure still shows black, then it is the problem with mapbox_style. Change it to the relevant requirement.
mapbox_style='carto-darkmatter'
As a whole:
df=pd.read_csv("/content/COVID-19_Cases_US.csv")
fig=px.scatter_mapbox(df, lat='Lat', lon='Long_', hover_name='Province_State', size='Confirmed',color='Confirmed',mapbox_style='carto-darkmatter',template='plotly_dark',zoom=0, size_max=70)
fig.write_html("Time_series_county_JH.html")
pio.show()
Result:
Update:
for mapbox_style = 'open-street-map' and code:
df=pd.read_csv("/content/COVID-19_Cases_US.csv")
fig=px.scatter_mapbox(df, lat='Lat', lon='Long_', hover_name='Province_State', size='Confirmed',color='Confirmed',mapbox_style='open-street-map',template='plotly_dark',zoom=4, size_max=70)
fig.write_html("Time_series_county_JH.html")
fig.show()
Here is the result:

plotly does not show the plots in google colaboratory

I have a dataframe named "Actuals", indexed by time. This is how I want to plot the Load column.
fig = go.Figure([go.Scatter(x=Actuals.index, y= Actuals['Load (kW)'])])
fig.show()
When I run this part, it executes without rising any error. but it doesn't display the figure. What is the issue and how can I resolve it?
I am using Google colaboratory
I should have added this line of code:
import plotly.io as pio
pio.renderers.default = 'colab'

plotly no space between pie chart and legend

I'm using plotly and I ahave created pue chart. the problem is that it works on jupyter ntoebook but when I download the graph the legend is overlap with the chart.
This is the plot on jupyter notebook:
but when I download it it as png it looks like this:
as you can see the legend items have very long names, but i'm not sure that cause the problem. Is there any way to control the spacing between the chart to the legend?
Edit: code sample:
import plotly.express as px
import plotly.graph_objects as go
fig = px.pie(df, values='count', names='LC', title='Land cover')
fig.update_layout(title_x=0.48)
fig.show()
I have also tried to play with the location of the legend this way:
fig.update_layout(title_x=0.48,legend={"x" : 1.7, "y" : 1})
but as I said, in jupyter notebook it worls but in the PNG is overlap just the same, even when X is equal to 3:

Multiple plotly plots on 1 page without subplot

I want to have multiple plotly plots on 1 html page without using the tools.make_subplots method. (I dont want to use that since I find that its not easy to read and I want a unique legend & layout in each of the subplot panels).
I want to define 2 figures with their own unique layouts, and arrange them arbitrarily on the page. I think I know how to do this with dash using the html.Div object, but I was wondering if there was an easy way to do this using only plotly?
I encountered the very same problem and followed the solution posted here:
Plotly: Plot multiple figures as subplots by Esostack
However, when I dumped the html of multiple figures into a single text file, I found the file size increasing by 5MB per figure that I add. 99.9% of this is caused by java script stuff that is added by plotly to make the plots interactive. Luckily, they also implemented a parameter to specify if you want to include the js or not. So you need to include it only for the first figure and skip it for the rest, like it is done in the following function. Hope that helps:
def figures_to_html(figs, filename):
'''Saves a list of plotly figures in an html file.
Parameters
----------
figs : list[plotly.graph_objects.Figure]
List of plotly figures to be saved.
filename : str
File name to save in.
'''
import plotly.offline as pyo
dashboard = open(filename, 'w')
dashboard.write("<html><head></head><body>" + "\n")
add_js = True
for fig in figs:
inner_html = pyo.plot(
fig, include_plotlyjs=add_js, output_type='div'
)
dashboard.write(inner_html)
add_js = False
dashboard.write("</body></html>" + "\n")
So, in conclusion, I have not found a way to do this purely with plotly. Below is my code for doing this with Dash, which has been working quite well:
Step 1: make a few plotly plots
import plotly.offline as pyo
import plotly.graph_objs as go
import plotly as py
fig1 = go.Scatter(y=[1,2,3])
fig2 = go.Scatter(y=[3,2,1])
plots = [fig1, fig2]
Step 2: Make dash Div objects:
app = dash.Dash()
layout = html.Div(
[html.Div(plots[i]) for i in range(len(plots))],
style = {'margin-right': '0px'}
)
Step 3: Run dash
app.layout = layout
app.run_server(port=8052)

Plotting chart with rounded rectangle in Python

I found an interesting chart illustrating the specific bands of different trace chemical atmospheric species that can be used for detecting on satellite.
The figure above use rounded rectangle presented for the spectral measurement range.
I want to reproduce this kind of art with python.
For now, I could use Plotly package for plotting table in the same style.
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF
fig = go.Figure()
data_matrix = [['Tracer gas/nm', '200', '300','400','500'],['HCHO', "", ],
['CHOCHO',],['BrO', ], ['O3', ],['O2', ],['NO2',]]
table = FF.create_table(data_matrix)
py.iplot(table, filename='simple_table')
# py.image.save_as(fig, filename='a-simple-plot.png')
The figure shows like this:
But I found two tricky problems:
(1) I couldn't save the chart into figure.
(2) I couldn't plot the rounded rectangle on the chart.
Any advice with better solution would be appreciated!

Categories