ipython plotly map render on a django template - python

This is what I am doing in an ipython notebook where the plotly graphs and everything gets generated without fail. After that I am taking the html form of the notebook and embedding it in a django template where everything is working other than the plotly graphs. I am not sure what needs to be done thats why I also tried installing plotly on npm and also including a reference to plotly.js through my template. Below are the codes.
import pandas as pd
import numpy as np
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly.graph_objs import *
init_notebook_mode()
data = pd.read_csv("storage/AviationDataUp.csv")
useful_columns = ['Event.Date', 'Location', 'Country', 'Latitude', 'Longitude', 'Purpose.of.Flight',\
'Total.Fatal.Injuries','Number.of.Engines','Air.Carrier']
data = data[useful_columns]
data = data[data['Country']=='United States']
accident_trace = Scattergeo(
locationmode = 'ISO-3',
lon = data['Longitude'],
lat = data['Latitude'],
mode = 'markers',
marker = dict(
size = 2,
opacity = 0.75,
color="rgb(0, 130, 250)"),
name = 'Accidents'
)
layout = dict(
title = 'Aviation Accidents in USA',
geo = dict(
scope = 'usa',
projection = dict(),
showland = True,
landcolor = 'rgb(250, 250, 250)',
subunitwidth = 1,
subunitcolor = 'rgb(217, 217, 217)',
countrywidth = 1,
countrycolor = 'rgb(217, 217, 217)',
showlakes = True,
lakecolor = 'rgb(255, 255, 255)'
) )
figure = dict(data=Data([accident_trace]), layout=layout)
iplot(figure)

Related

Not able to view US-states heatmap

I have written the following code to heat heatmap of US-States. But I am unable to get the output image in Google Colab.
State codes are two alphabet codes for a particular state of the US.
temp = pd.DataFrame(project_data.groupby("school_state")["project_is_approved"].apply(np.mean)).reset_index()
temp.columns = ['state_code', 'num_proposals']
scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'],\
[0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']]
data = [ dict(
type='choropleth',
colorscale = scl,
autocolorscale = False,
locations = temp['state_code'],
z = temp['num_proposals'].astype(float),
locationmode = 'USA-states',
text = temp['state_code'],
marker = dict(line = dict (color = 'rgb(255,255,255)',width = 2)),
colorbar = dict(title = "% of pro")
) ]
layout = dict(
title = 'Project Proposals % of Acceptance Rate by US States',
geo = dict(
scope='usa',
projection=dict( type='albers usa' ),
showlakes = True,
lakecolor = 'rgb(255, 255, 255)',
),
)
fig = dict(data=data, layout=layout)
offline.iplot(fig, filename='us-map-heat-map')
I have imported following libraries:
from chart_studio import plotly
import plotly.offline as offline
import plotly.graph_objs as go
offline.init_notebook_mode()
from collections import Counter
import chart_studio.plotly as py
Try the following code with your data:
(I tried putting your variables in the correct spots)
choropleth = go.Choropleth(
locations=temp['state_code'],
locationmode='USA-states',
z = temp['num_proposals'].astype(float),
zmin = 0,
zmax = max(temp['num_proposals'].astype(float)),
colorscale=scl,
autocolorscale=False,
text='Proposals',
marker_line_color='white',
colorbar_title="% Acceptance Rate"
)
fig = go.Figure(data=choropleth)
fig.update_layout(
title_text='Project Proposals % of Acceptance Rate by US States',
geo = dict(
scope='usa',
projection=go.layout.geo.Projection(type = 'albers usa'),
showlakes=True,
lakecolor='rgb(255, 255, 255)'),
)
fig.show()
This code works by creating the Plotly Choropleth Graph Object with your data, then loading that object into a Plotly Figure Graph Object, then updating the layout (for proper titles and zooms), and finally displaying the figure.

Plotly Sankey diagram group label and color

I'm creating a sankey diagram using plotly and there is the built in method to use 'group' to combine nodes. However, when I use this the color of this node will be black and no label is showing. This is expected as the colors of the grouped nodes could vary. However, I don't see how I can set the color of the group. Same goes for the label.
Is there a way to define this?
example code:
import plotly.graph_objs as go
from plotly.offline import plot
value = [3,5,2,4,6]
source = [0,0,1,0,3]
target = [1,4,2,3,4]
color = ["blue","yellow","orange","orange","purple"]
label = ["A","B","C1","C2","D"]
data = dict(
type='sankey',
arrangement = 'freeform',
node = dict(
pad = 15,
thickness = 20,
line = dict(
color = "black",
width = 0.1
),
groups = [[2,3]],
label = label,
color = color,
),
link = dict(
source = source,
target = target,
value = value,
)
)
layout = dict(
title = "Sankey test",
font = dict(
size = 10
)
)
f = go.FigureWidget(data=[data], layout=layout)
plot(f)
Which renders:
Since I'm getting the following error with your snippet:
ValueError: Invalid property specified for object of type plotly.graph_objs.sankey.Node: 'groups'
And since I don't know what versions you are running of plotly, python (and Jupyter Notebook?), I would simply suggest that you restructure your source data and do the C1 and C2 grouping into simply C before you build your plot. And keep in mind that Links are assigned in the order they appear in dataset and that node colors are assigned in the order that the plot is built.
Plot:
Code:
# imports
import pandas as pd
import numpy as np
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
# settings
init_notebook_mode(connected=True)
# Nodes & links
nodes = [['ID', 'Label', 'Color'],
[0,'A','blue'],
[1,'B','yellow'],
[2,'C','orange'],
[3,'D','purple'],
]
# links with your data
links = [['Source','Target','Value','Link Color'],
[0,1,3,'rgba(200, 205, 206, 0.6)'],
[0,2,5,'rgba(200, 205, 206, 0.6)'],
[0,3,5,'rgba(200, 205, 206, 0.6)'],
[1,2,6,'rgba(200, 205, 206, 0.6)'],
[2,3,6,'rgba(200, 205, 206, 0.6)'],
]
# Retrieve headers and build dataframes
nodes_headers = nodes.pop(0)
links_headers = links.pop(0)
df_nodes = pd.DataFrame(nodes, columns = nodes_headers)
df_links = pd.DataFrame(links, columns = links_headers)
# Sankey plot setup
data_trace = dict(
type='sankey',
domain = dict(
x = [0,1],
y = [0,1]
),
orientation = "h",
valueformat = ".0f",
node = dict(
pad = 10,
# thickness = 30,
line = dict(
color = "black",
width = 0
),
label = df_nodes['Label'].dropna(axis=0, how='any'),
color = df_nodes['Color']
),
link = dict(
source = df_links['Source'].dropna(axis=0, how='any'),
target = df_links['Target'].dropna(axis=0, how='any'),
value = df_links['Value'].dropna(axis=0, how='any'),
color = df_links['Link Color'].dropna(axis=0, how='any'),
)
)
layout = dict(
title = "Sankey Test",
height = 772,
font = dict(
size = 10),)
fig = dict(data=[data_trace], layout=layout)
iplot(fig, validate=False)
My system info:
The version of the notebook server is: 5.6.0
The server is running on this version of Python:
Python 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)]

Choropleth in Plotly python for USA is Blank

import os
import seaborn as sns
print(os.listdir("../input"))
df=pd.read_csv("../input/gun-violence-data_01-2013_03-2018.csv")
//GUN
violence dataset from kaggle//
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected=True)
import plotly.graph_objs as go
b=df.state.value_counts().sort_values()
ba=pd.DataFrame(b)
ans=ba.reset_index(inplace=True)
//creating a dataframe only containing the state names of USA and its count//
data = [ dict(type='choropleth',
autocolorscale = False,
locations = ba['index'],
z = ba['state'],
locationmode = 'USA-states',
text = ba['index'],
colorscale='Viridis' ) ]
layout = dict(
title = 'US',
geo = dict(
scope='usa',
projection=dict( type='albers usa' ),
showlakes = True,
lakecolor = 'rgb(255, 165, 255)'),)
fig = go.Figure( data=data,layout=layout )
iplot(fig)
However, whenever I run this code, Only a blank image of USA is obtained,
which is blank and shows no values. please help!

Display python plotly graph in RMarkdown html document

Why plotly package of python can not display figure in RMarkdown but matplotlib can? For example:
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
```
```{r}
library(plotly)
subplot(
plot_ly(mpg, x = ~cty, y = ~hwy, name = 'default'),
plot_ly(mpg, x = ~cty, y = ~hwy) %>%
add_markers(alpha = 0.2, name = 'alpha'),
plot_ly(mpg, x = ~cty, y = ~hwy) %>%
add_markers(symbols = I(1), name = 'hollow')
)
```
```{python}
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np
plotly.tools.set_credentials_file(username='xxx', api_key='xxx')
N = 500
trace0 = go.Scatter(x = np.random.randn(N), y = np.random.randn(N) + 2, name = "Above", mode = "markers",
marker = dict(size = 10, color = "rgba(152, 0, 0, .8)", line = dict(width = 2, color = "rgb(0,0,0)")))
trace1 = go.Scatter(x = np.random.randn(N), y = np.random.randn(N) - 2, name = "below", mode = "markers",
marker = dict(size = 10, color = "rgba(255, 182, 193, .9)", line = dict(width = 2, color = "rgb(0,0,0)")))
data = [trace0, trace1]
layout = dict(title = "Styled Scatter", yaxis = dict(zeroline = False), xaxis = dict(zeroline=False))
fig = dict(data = data, layout = layout)
py.iplot(fig, filename = "styled-scatter")
```
The R code can work well, but the python code can not dispay the figure, what is wrong with the code?
Here is what I did:
used plotly offline:
replace import plotly.plotly as py by import plotly.offline as py
no need to set username and api key in offline mode.
used py.plot(fig, filename = "styled-scatter.html", auto_open=False):
py.iplot() is for Jupyter notebooks (it embeds the plot directly into the Notebook)
auto_open = False argument is to avoid that the plot pops up.
embedded the html plot into the Rmarkdown by using the following:
```{r, echo=FALSE}
htmltools::includeHTML("styled-scatter.html")
```
and here is the result:

Choropleth world map not showing all countries

I wanted to make a choropleth world map, which shows the hits(number of searches) of a word, on a World map.
Following is the code:
import plotly
import plotly.offline
import pandas as pd
df = pd.read_excel('F:\\Intern\\csir\\1yr\\news\\region_2016_2017.xlsx')
df = df.query('keyword==["addiction"]')
scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'],\
[0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']]
data = [dict(
type='choropleth',
colorscale=scl,
locations = df['location'],
z = df['hits'].astype(int),
locationmode = "country names",
autocolorscale = False,
reversescale = False,
marker = dict(
line = dict (
color = 'rgb(180,180,180)',
width = 0.5)),
colorbar = dict(
autotick = False,
title = 'Hits'),)]
layout = dict(
title = 'Addiction keyword 1yr analysis',
geo = dict(
showframe = False,
showcoastlines = False,
projection = dict(
type = 'Mercator'
)
)
)
fig = dict(data = data,layout = layout)
plotly.offline.plot(fig,validate=False,filename = 'd3-world-map.html')
And the plotted map is:
As one can see clearly, many countries are missing. This may be due to the fact that many countries didn't have entries which explicitly stated that they have zero hits.
I don't want to explicitly do that with my data. Is there any other way out of this? So that we can see all of the countries.
Data set can be found here.
Note that the dataset that I've linked is an .csv file whereas the file used in the program is an .xlsx version of the file.
You need to turn on country outlines under layout...
"geo":{
"countriescolor": "#444444",
"showcountries": true
},

Categories