Can't get map to appear in Python Data Visualization - python

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:

Related

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.

Matplotlib save to pdf not showing hatch marks in bar plot -- potential bug?

I am using matplotlib version 3.1.1 on an ubuntu 18.04 machine and have tried this code in both python 3.6.8 and 3.7.4 on 2 different boxes.
The problem is that when there are more than 10 items the color repeats itself and I made a quick change to make hatch marks to differentiate. While this works well in display, the hatches do not show up when I savefig("*.pdf"). savefig("*.png") seems to work fine as seen in the figures below.
I have searched for this issue in multiple places but can't seem to find a solution that works. I have also tried PdfPages.
Simple code and output are attached below. I appreciate any suggestions.
Code:
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
matplotlib.__version__ #3.1.1
df=pd.DataFrame({'A':[0.1]*12, 'B':[0.1]*12}).T
tit='title'
ax=df.plot.bar(figsize=(11,8.5),stacked=True,title=tit)
nrows=len(df)
bars = ax.patches
hatches=['','-', '+', 'x','/','//','O','o','\\','\\\\']*nrows*10 #times rows*colors
#
hatches.sort()
hatches=hatches[0:len(bars)]
i=0
for bar in bars:# goes down a column with same color, then next with diff color and so on.
bar.set_hatch(hatches[i])
#bar.text('1')
#print(bar)
i+=1
ax.legend(#loc='lower center', loc='upper center',bbox_to_anchor=(0.5, -.05,0,0),fancybox=True, shadow=True, ncol=5,fontsize=5.5)
#plt.savefig('barhatch.png')
plt.savefig('barhatch.pdf')
screenshot of actual plot:
screenshot of actual plot
savefig("out.png"):
screenshot of the pdf as I can't seem to attach:
Try to use different facecolor for the filled space and edgecolor for the hatch.
I suppose the hatches are there but shown in the same color as the filled space below. I have experienced something similar with fill_between and found a solution in this GitHub discussion.

Printing image in r-markdown using matplotlib and python code

I am trying to run the python code using the R-Markdown file (RMarkdown to pdf).
What I achieved till now -
1- I am able to configure my python engine using knitr and reticulate library
2- I am able to execute my python codes.
What I tried -
1- I tried all the methods which are discussed in this forum, but nothing is working out.
2- I also tried to save the image,(as one of the posts here suggests), but that also is not working.
My problem -
1- When I am trying to plot a graph using matlplotlib and command plt.imshow() and plt.show(), it's not printing the image in the output. Rather it's showing the image in a separate window. You can see my results in the attached image.
Result_of_my_code
Here is my code
```{r setup, include=FALSE}
library(knitr)
library(reticulate)
knitr::knit_engines$set(python = reticulate::eng_python)
```
```{python}
import numpy as np
import os
import torch
import torchvision.datasets as dsets
import matplotlib.pyplot as plt
print(os.getcwd())
os.chdir('D:\\1st year\\Python codes\\CIFR Analysis\\self contained analysis')
print(os.getcwd())
train_mnist = dsets.MNIST("../data", train=True)
test_mnist = dsets.MNIST("../data", train= False)
print(len(train_mnist))
#print(train_mnist[0][0])
plt.imshow(train_mnist[0][0], cmap="gray")
#plt.savefig("trainzero.png")
plt.show()
```
Kindly, help me to fix this issue, as I want to compile my python codes using the R markdown file.
thanks
So with R Markdown, you have to do some things a little differently. In the following, I have a dataframe with two series created by concatenating them. The original plotting code in the Jupyter Notebook is as follows and just printed out the series.
# make a plot of model fit
train.plot(figsize=(16,8), legend=True)
backtest.plot(legend=True);
However, it does not work with way with R Markdown. Then with plotting, you always have to assign them, and with the code below, you get the same plot.
dfreg = pd.concat([reg, backtest], axis = 1)
ax = dfreg.plot(figsize=(16,8), legend = True)
ax1 = predictions.plot(legend=True)
plt.show()
This is common with other plotting functions like plot_acf() too.

Python3 Plotly markers always circle

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.

Categories