Plotting chart with rounded rectangle in Python - 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!

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:

How to change the edgecolor of an Histogram in plotly?

I'm trying to change from matplotlib to plotly and I have to relearn every basic move.
One of my habit was to change the edge color of every histogram I made to white so it is easier to see the bars.
On matplotlib, I would do it like that :
import matplotlib.pyplot as plt
import numpy as np
vals = np.random.rand(50)
plt.hist(vals, edgecolor='white');
Which gives me :
I suppose there is a way to do it with plotly but I searched in the doc and other stackoverflow questions and haven't found it yet.
Closest way (that make me believe it is somehow possible): setting the template of the figure to a template using white edgecolor
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import numpy as np
vals = np.random.rand(50)
fig = px.histogram(x=vals, template="simple_white")
fig.show()
I also tried to examinate the template simple_white and to look for the param that was making the edges to be white but this didn't lead to anything (if you know what this param is, the answer interests me even more !)
There is function called fig.update_traces you can increase marker(edge) width and change color to 'White' like:
fig = px.histogram(x=vals)
fig.update_traces(marker_line_width=1,marker_line_color="white")
fig.show()
Reference: https://plotly.com/python/reference/histogram/
plotly.graph_objects.Histogram accepts a Marker as input argument. That means you can enable the borders and specify their color using a marker:
import plotly.graph_objects as go
fig.show()
go.Histogram(x=vals,
marker=dict(line=dict(width=0.8,
color="white")))
To see all other parameters of a marker, see the docs here.

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:

Animated multiseries Line Graph using Plotly Express (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.

Detailed date in cursor pos on pyplot charts

Let's say there's a time series that I want to plot in matplotlib:
dates = pd.date_range(start='2011-01-01', end='2012-01-01')
s = pd.Series(np.random.rand(1, len(dates))[0], index=dates)
The GUI backends in matplotlib have this nice feature that they show the cursor coordinates in the window. When I plot pandas series using its plot() method like this:
fig = plt.figure()
s.plot()
fig.show()
the cursor's x coords are shown in full yyyy-mm-dd at the bottom of the window as you can see on pic 1.
However when I plot the same series s with pyplot:
fig = plt.figure()
plt.plot(s.index, s.values)
fig.show()
full dates are only shown when I zoom in and in the default view I can only see Mon-yyyy (see pic 2) and I would see just the year if the series were longer.
In my project there are functions for drawing complex, multi-series graphs from time series data using plt.plot(), so when I view the results in GUI I only see the full dates in the close-ups. I'm using ipython3 v. 4.0 and I'm mostly working with the MacOSX backend, but I tried TK, Qt and GTK backends on Linux with no difference in the behavior.
So far I've got 2 ideas on how to get the full dates displayed in GUI at any zoom level:
rewrite plt.plot() to pd.Series.plot()
use canvas event handler to get the x-coord from the cursor pos and print it somewhere
However before I attempt any of the above I need to know for sure if there is a better quicker way to get the full dates printed in the graph window. I guess there is, because pandas is using it, but I couldn't find it in pyplot docs or examples or elsewhere online and it's none of these 2 calls:
ax.xaxis_date()
fig.autofmt_xdate()
Somebody please advise.
Hooks for formatting the info are Axes.format_coord or Axes.fmt_xdata. Standard formatters are defined in matplotlib.dates (plus some additions from pandas). A basic solution could be:
import matplotlib.dates
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
dates = pd.date_range(start='2011-01-01', end='2012-01-01')
series = pd.Series(np.random.rand(len(dates)), index=dates)
plt.plot(series.index, series.values)
plt.gca().fmt_xdata = matplotlib.dates.DateFormatter('%Y-%m-%d')
plt.show()

Categories