Python3 Plotly markers always circle - python

I have for example the following plotly Scatter(severly stripped from other code, all code available at below repo. This always draws as circles and not as pentagons as symbol=13 should per the documentation.
https://plot.ly/python/reference/
https://github.com/CPDTAC/CPViewInsights_Client/blob/378f4b5583b3263daf6fef56a3c557cd26053e45/cpviewdb.py#L120
I had been using plotly via Dash and this was working. Converted most of it to a pyqt gui and for reasons for which I hope you all can answer, marker symbols aren't working for me.
return_data = []
policy_times = [some list of tuples]
policy_trace = plotly.graph_objs.Scattergl(
x=[i[0] for i in policy_times],
y=[i[1] for i in policy_times],
name='Policy Install',
mode='markers',
marker=dict(symbol=13, size=20))
return_data.append(policy_trace)
layout = plotly.graph_objs.Layout(showlegend=True)
figure = plotly.graph_objs.Figure(data=return_data, layout=layout)
plotly.offline.plot(figure, filename=filename)

Not sure the reasoning but this was caused due to using Scattergl instead of Scatter.

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:

Python plotly sankey export broken

I have a python sankey chart which works well when exporting the html but looks completely broken when exporting it to other file formats
import plotly.graph_objects as go
fig = go.Figure(data=[go.Sankey(
node = dict(label = data["label"]),
link = dict(source = data["source"],target = data["target"],value = data["value"])
)])
fig.write_image("sankey.svg")
fig.write_image("sankey.eps")
fig.write_image("sankey.png")
fig.write_html("sankey.html")
HTML Screenshot
PNG Export (SVG, EPS differ a bit but also look broken)
I'm using python 3.8.5 with the kaleido 0.0.3 engine.
Additionally, I've tried Orca 1.2.1 but got the same results.
The answer actually is very easy. Tough most of the charts can figure out the required size on their own, the sankey chart obviously can't. So basically you just have to set dimensions for all exports on sankey charts (yes even for vector graphics like eps and svg).
Also worth mentioning is that a minimum size is required. While my example now looks satisfying with 1920x1080, a size of 1280x720 looks broken even with vector-graphics.
fig = go.Figure(...)
fig.update_layout(width=1920, height=1080)
fig.write_image(...)

Python plotly logo disapering from chart

I have to create a simple report that show one data table and have two logos in the top corners. The code below worked in a previous project but now that I’m reusing it on a new computer for a new project it wont show the logos.
I get no error message. Same version of plotly and python "plotly==4.6.0" "Python 3.6.1"
Please note that the only thing that changed is the data shown in the datatable.
import plotly.graph_objects as go
import pandas as pd
traces = go.Table(
header=dict(values=list(df.columns),
align='left'),
cells=dict(
values=df.T.values.tolist(),
align='left'))
layout = go.Layout(
title='Report <br> {}'.format( report_date),
title_x=0.5,
paper_bgcolor='#FFFFFF',
margin = {'t':100, 'b':40, 'r':40, 'l':40}
,images=[
dict(
source='assets\\MiniLogo.png',
xref='paper',yref='paper',
x=1,y=1.05,
sizex=0.2, sizey=0.2,
xanchor="right", yanchor="bottom"),
dict(
source='assets\\Titlelogo.png',
xref='paper',yref='paper',
x=0,y=1.05,
sizex=0.2, sizey=0.2,
xanchor="left", yanchor="bottom")
]
)
fig = go.Figure(
data=traces
,layout=layout)
fig.show()
I think the problem is within the source argument in your layout. I've used your code with this image URL instead of a relative path and it works perfectly and here is a screenshot knowing that I've used a simple table as my df:
In my opinion, you have two options to overcome that:
Upload these images to a cloud-service and use their URLs instead.
Or according to this Plolty community thread, you can use Pillow.Image class to read the image from your local machine. You can install it easily by running pip install pillow and modify your code to be like so:
from PIL import Image
layout= go.Layout(images= [dict(
source= Image.open('assets\\MiniLogo.png'),
...)])

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.

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)

Categories