Change parameters for plotly maps - python

I'm trying to plot the intensity of CO2 emissions per country using plotly ,
Most of the countries don't even exceed 10k, but the color range is from 0 to 35k , how do I change that?
Here's my code:
def enable_plotly_in_cell():
import IPython
from plotly.offline import init_notebook_mode
display(IPython.core.display.HTML('''<script src="/static/components/requirejs/require.js"></script>'''))
init_notebook_mode(connected=False)
data = dict(type = 'choropleth',
locations = fmmcgrf['Entity'],
locationmode = 'country names',
z = fmmcgrf['CO2'],
text = fmmcgrf['Entity'],
colorbar = {'title':'CO2'})
layout = dict(title = 'Co2',
geo = dict(showframe = False,
projection = {'type': 'winkel tripel'}))
map = go.Figure(data = [data], layout=layout)
enable_plotly_in_cell()
map.show()

I customized the color bar with the example from the official reference.
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
fig = go.Figure(data=go.Choropleth(
locations = df['CODE'],
z = df['GDP (BILLIONS)'],
text = df['COUNTRY'],
colorscale = 'Blues',
autocolorscale=False,
reversescale=True,
marker_line_color='darkgray',
marker_line_width=0.5,
colorbar_tickprefix = '$',
colorbar_tickvals=[0,10000,15000],# update
colorbar_title = 'GDP<br>Billions US$',
))
fig.update_layout(
title_text='2014 Global GDP',
geo=dict(
showframe=False,
showcoastlines=False,
projection_type='equirectangular'
),
)
fig.show()

Related

why bokeh chart sometime does not display colors

Hi could someone point me what I do wrong: some time bokeh does not display color. If run the script there will be only red points, but when I change the 'green' to the 'lime' there will be points of two colors - why? what do I wrong?
import numpy as np
from scipy.signal import find_peaks
# Find peaks
max_peaks, max_other = find_peaks(price, height=0.1)
print(len(max_peaks))
min_peaks, min_other = find_peaks(-price)
print(len(min_peaks))
colors = np.full(len(price), 'None')
colors[max_peaks] = 'red'
colors[min_peaks] = 'green'
from bokeh.models import CrosshairTool
crosshair = CrosshairTool(dimensions='both')
width=1000
height = 600
price_dates = df['date'].to_numpy()
price_dates_dt = np.apply_over_axes(convert_int_to_datetime, price_dates, axes=0)
price_dates_str = np.apply_over_axes(convert_int_to_datetime_to_str, price_dates, axes=0)
price_source = ColumnDataSource(data=dict(
date = price_dates_dt,
date_str = price_dates_str,
price=df['close'].to_numpy(),
color=colors
))
f1 = figure(title=f'price', x_axis_type='datetime', tools='pan,wheel_zoom,box_zoom,reset,save,box_select,zoom_in,zoom_out, hover', sizing_mode='stretch_width',plot_width=width, plot_height=height)
f1.toolbar.logo = None
f1.add_tools(crosshair)
price_l = f1.line(source=price_source, x='date', y='price', legend_label='price', line_color='gray', line_dash='solid', line_width=0.8)
price_s = f1.scatter(source=price_source, x='date', y='price', legend_label='price', fill_color='color', line_color='color', size=2)
f1.add_tools(HoverTool(renderers=[price_s, price_l], tooltips=[
('index', '$index'),
('(x,y)', '($x{%F}, $y{0.00})'),
# ('date', '#date'),
('date_str', '#date_str'),
('price', '#price{0.00}')],
formatters={
'#date': 'datetime',
'#{price}': 'printf', }))
f1.legend.location = 'top_left'
f1.legend.click_policy = 'hide'
f1.xaxis.axis_label = 'Time'
f1.yaxis.axis_label = 'price'
f1.background_fill_color = '#dfe9f0'
# f1.background_fill_alpha = 0.5
f1.xgrid.grid_line_color='white'
f1.ygrid.grid_line_color='white'
show(f1)

Plotly Python update figure with dropMenu

i am currently working with plotly i have a function called plotChart that takes a dataframe as input and plots a candlestick chart. I am trying to figure out a way to pass a list of dataframes to the function plotChart and use a plotly dropdown menu to show the options on the input list by the stock name. The drop down menu will have the list of dataframe and when an option is clicked on it will update the figure in plotly is there away to do this. below is the code i have to plot a single dataframe
def make_multi_plot(df):
fig = make_subplots(rows=2, cols=2,
shared_xaxes=True,
vertical_spacing=0.03,
subplot_titles=('OHLC', 'Volume Profile'),
row_width=[0.2, 0.7])
for s in df.name.unique():
trace1 = go.Candlestick(
x=df.loc[df.name.isin([s])].time,
open=df.loc[df.name.isin([s])].open,
high=df.loc[df.name.isin([s])].high,
low=df.loc[df.name.isin([s])].low,
close=df.loc[df.name.isin([s])].close,
name = s)
fig.append_trace(trace1,1,1)
fig.append_trace(go.Scatter(x=df.loc[df.name.isin([s])].time, y=df.loc[df.name.isin([s])].BbandsMid, mode='lines',name='MidBollinger'),1,1)
fig.append_trace(go.Scatter(x=df.loc[df.name.isin([s])].time, y=df.loc[df.name.isin([s])].BbandsUpp, mode='lines',name='UpperBollinger'),1,1)
fig.append_trace(go.Scatter(x=df.loc[df.name.isin([s])].time, y=df.loc[df.name.isin([s])].BbandsLow, mode='lines',name='LowerBollinger'),1,1)
fig.append_trace(go.Scatter(x=df.loc[df.name.isin([s])].time, y=df.loc[df.name.isin([s])].vwap, mode='lines',name='VWAP'),1,1)
fig.append_trace(go.Scatter(x=df.loc[df.name.isin([s])].time, y=df.loc[df.name.isin([s])].STDEV_1, mode='lines',name='UPPERVWAP'),1,1)
fig.append_trace(go.Scatter(x=df.loc[df.name.isin([s])].time, y=df.loc[df.name.isin([s])].STDEV_N1, mode='lines',name='LOWERVWAP'),1,1)
fig.append_trace(go.Scatter(x=df.loc[df.name.isin([s])].time, y=df.loc[df.name.isin([s])].KcMid, mode='lines',name='KcMid'),1,1)
fig.append_trace(go.Scatter(x=df.loc[df.name.isin([s])].time, y=df.loc[df.name.isin([s])].KcUpper, mode='lines',name='KcUpper'),1,1)
fig.append_trace(go.Scatter(x=df.loc[df.name.isin([s])].time, y=df.loc[df.name.isin([s])].KcLow, mode='lines',name='KcLow'),1,1)
trace2 = go.Bar(
x=df.loc[df.name.isin([s])].time,
y=df.loc[df.name.isin([s])].volume,
name = s)
fig.append_trace(trace2,2,1)
# fig.update_layout(title_text=s)
graph_cnt=len(fig.data)
tr = 11
symbol_cnt =len(df.name.unique())
for g in range(tr, graph_cnt):
fig.update_traces(visible=False, selector=g)
#print(g)
def create_layout_button(k, symbol):
start, end = tr*k, tr*k+2
visibility = [False]*tr*symbol_cnt
visibility[start:end] = [True,True,True,True,True,True,True,True,True,True,True]
return dict(label = symbol,
method = 'restyle',
args = [{'visible': visibility[:-1],
'title': symbol,
'showlegend': False}])
fig.update(layout_xaxis_rangeslider_visible=False)
fig.update_layout(
updatemenus=[go.layout.Updatemenu(
active = 0,
buttons = [create_layout_button(k, s) for k, s in enumerate(df.name.unique())]
)
])
fig.show()
i am trying to add annotations to the figure it will be different for each chart below is how i had it setup for the single chart df['superTrend'] is a Boolean column
for i in range(df.first_valid_index()+1,len(df.index)):
prev = i - 1
if df['superTrend'][i] != df['superTrend'][prev] and not np.isnan(df['superTrend'][i]) :
#print(i,df['inUptrend'][i])
fig.add_annotation(x=df['time'][i], y=df['open'][i],
text= 'Buy' if df['superTrend'][i] else 'Sell',
showarrow=True,
arrowhead=6,
font=dict(
#family="Courier New, monospace",
size=20,
#color="#ffffff"
),)
I adapted an example from the plotly community to your example and created the code. The point of creation is to create the data for each subplot and then switch between them by means of buttons. The sample data is created using representative companies of US stocks. one issue is that the title is set but not displayed. We are currently investigating this issue.
import yfinance as yf
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
symbols = ['AAPL','GOOG','TSLA']
stocks = pd.DataFrame()
for s in symbols:
data = yf.download(s, start="2021-01-01", end="2021-12-31")
data['mean'] = data['Close'].rolling(20).mean()
data['std'] = data['Close'].rolling(20).std()
data['upperBand'] = data['mean'] + (data['std'] * 2)
data.reset_index(inplace=True)
data['symbol'] = s
stocks = stocks.append(data, ignore_index=True)
def make_multi_plot(df):
fig = make_subplots(rows=2, cols=1,
shared_xaxes=True,
vertical_spacing=0.03,
subplot_titles=('OHLC', 'Volume Profile'),
row_width=[0.2, 0.7])
for s in df.symbol.unique():
trace1 = go.Candlestick(
x=df.loc[df.symbol.isin([s])].Date,
open=df.loc[df.symbol.isin([s])].Open,
high=df.loc[df.symbol.isin([s])].High,
low=df.loc[df.symbol.isin([s])].Low,
close=df.loc[df.symbol.isin([s])].Close,
name=s)
fig.append_trace(trace1,1,1)
trace2 = go.Scatter(
x=df.loc[df.symbol.isin([s])].Date,
y=df.loc[df.symbol.isin([s])].upperBand,
name=s)
fig.append_trace(trace2,1,1)
trace3 = go.Bar(
x=df.loc[df.symbol.isin([s])].Date,
y=df.loc[df.symbol.isin([s])].Volume,
name=s)
fig.append_trace(trace3,2,1)
# fig.update_layout(title_text=s)
# Calculate the total number of graphs
graph_cnt=len(fig.data)
# Number of Symbols
symbol_cnt =len(df.symbol.unique())
# Number of graphs per symbol
tr = 3
# Hide setting for initial display
for g in range(tr, graph_cnt):
fig.update_traces(visible=False, selector=g)
def create_layout_button(k, symbol):
start, end = tr*k, tr*k+2
visibility = [False]*tr*symbol_cnt
# Number of graphs per symbol, so if you add a graph, add True.
visibility[start:end] = [True,True,True]
return dict(label = symbol,
method = 'restyle',
args = [{'visible': visibility[:-1],
'title': symbol,
'showlegend': True}])
fig.update(layout_xaxis_rangeslider_visible=False)
fig.update_layout(
updatemenus=[go.layout.Updatemenu(
active = 0,
buttons = [create_layout_button(k, s) for k, s in enumerate(df.symbol.unique())]
)
])
fig.show()
return fig.layout
make_multi_plot(stocks)

Choropleth map in Plotly: colours not showing correctly

Trying to make a choropleth map in plotly using some data I have in a csv file. Have created the following map:
my choromap
This isn't a correct display of the data however. Here is an excerpt of my csv file:
China,2447
...
Trinidad And Tobago,2
Turkey,26
Ukraine,8
United Arab Emirates,97
United States of America,2008
Based on this I'd expected China to appear in a similar colour to that which the US has loaded in, however it looks the same as countries with values of less than 200. Does anyone know what the reason for this is?
Here's my full code for reference:
import pandas as pd
import plotly as py
df = pd.read_csv('app_country_data_minus_uk.csv')
data = [dict(type='choropleth',
locations = df['Country'],
locationmode = 'country names',
z = df['Applications'],
text = df['Country'],
colorbar = {'title':'Apps per country'},
colorscale = 'Jet',
reversescale = False
)]
layout = dict(title='Application Jan-June 2018',
geo = dict(showframe=False,projection={'type':'mercator'}))
choromap = dict(data = data,layout = layout)
red = py.offline.plot(choromap,filename='world.html')
per your comment I would make sure that china is indeed 2447 and not something like 244. I would also follow the plotly documentation although you example code works.
import plotly.plotly as py
import pandas as pd
df = pd.read_csv('app_country_data_minus_uk.csv')
data = [ dict(
type = 'choropleth',
locations = df['Country'],
locationmode = 'country names',
z = df['Applications'],
colorscale = 'Jet',
reversescale = False,
marker = dict(
line = dict (
color = 'rgb(180,180,180)',
width = 0.5
) ),
colorbar = dict(
autotick = False,
tickprefix = '',
title = 'Apps per country'),
) ]
layout = dict(
title = 'app_country_data_minus_uk',
geo = dict(
showframe = True,
showcoastlines = True,
projection = dict(
type = 'Mercator'
)
)
)
fig = dict( data=data, layout=layout )
py.iplot( fig, validate=False, filename='d3-world-map' )
or if you want to plot it offline:
import plotly.plotly as py
import pandas as pd
import plotly
df = pd.read_csv('app_country_data_minus_uk.csv')
data = [ dict(
type = 'choropleth',
locations = df['Country'],
locationmode = 'country names',
z = df['Applications'],
colorscale = 'Jet',
reversescale = False,
marker = dict(
line = dict (
color = 'rgb(180,180,180)',
width = 0.5
) ),
colorbar = dict(
title = 'Apps per country'),
) ]
layout = dict(
title = 'app_country_data_minus_uk',
geo = dict(
showframe = True,
showcoastlines = True,
projection = dict(
type = 'Mercator'
)
)
)
fig = dict( data=data, layout=layout )
plotly.offline.plot(fig,filename='world.html')
If you use iplot you will be able to edit the chart and see the data in plotly to make sure your data looks correct

Plotly Geoscatter with Aggregation: show aggregation in hover Info

I have been trying to create a Geoscatter Plot with Plotly where the marker size should indicate the number of customers (row items) in one city (zip_city). I based my code on two templates from the Plotly documentation: United States Bubble Map and the aggregation part Mapping with Aggregates.
I managed to put together a code that does what I want, except for one drawback: when I hover over a bubble, I would like to see the name of the city plus number of customers (the result from the aggregation), so something like Aguadilla: 2. Can you help me on how to do this?
Here is my code (as a beginner with plotly, I am also open to code improvements):
import plotly.offline as pyo
import pandas as pd
df = pd.DataFrame.from_dict({'Customer': [111, 222, 555, 666],
'zip_city': ['Aguadilla', 'Aguadilla', 'Arecibo', 'Wrangell'],
'zip_latitude':[18.498987, 18.498987, 18.449732,56.409507],
'zip_longitude':[-67.13699,-67.13699,-66.69879,-132.33822]})
data = [dict(
type = 'scattergeo',
locationmode = 'USA-states',
lon = df['zip_longitude'],
lat = df['zip_latitude'],
text = df['Customer'],
marker = dict(
size = df['Customer'],
line = dict(width=0.5, color='rgb(40,40,40)'),
sizemode = 'area'
),
transforms = [dict(
type = 'aggregate',
groups = df['zip_city'],
aggregations = [dict(target = df['Customer'], func = 'count', enabled = True)]
)]
)]
layout = dict(title = 'Customers per US City')
fig = dict( data=data, layout=layout )
pyo.plot( fig, validate=False)
Update:
Can I access the result of the transforms argument directly in the data argument to show the number of customers per city?
You can create a list, that will contains what you want and then set text=list in data. Also do not forget specify hoverinfo='text'.
I am updated your code, so try this:
import pandas as pd
import plotly.offline as pyo
df = pd.DataFrame.from_dict({'Customer': [111, 222, 555, 666],
'zip_city': ['Aguadilla', 'Aguadilla', 'Arecibo', 'Wrangell'],
'zip_latitude':[18.498987, 18.498987, 18.449732,56.409507],
'zip_longitude':[-67.13699,-67.13699,-66.69879,-132.33822]})
customer = df['Customer'].tolist()
zipcity = df['zip_city'].tolist()
list = []
for i in range(len(customer)):
k = str(zipcity[i]) + ':' + str(customer[i])
list.append(k)
data = [dict(
type = 'scattergeo',
locationmode = 'USA-states',
lon = df['zip_longitude'],
lat = df['zip_latitude'],
text = list,
hoverinfo = 'text',
marker = dict(
size = df['Customer'],
line = dict(width=0.5, color='rgb(40,40,40)'),
sizemode = 'area'
),
transforms = [dict(
type = 'aggregate',
groups = df['zip_city'],
aggregations = [dict(target = df['Customer'], func = 'count', enabled = True)]
)]
)]
layout = dict(title = 'Customers per US City')
fig = dict(data=data, layout=layout)
pyo.plot(fig, validate=False)

Jupyter Notebook not ploting output using plotly

I am working on choropleth using plotly in Jupyter Notebook.I want to plot choropleth but its showing me empty output.I am working with offline plotly.In html its genrated chart successfuly but when i tried offline it shows me empty output.please tell me how i solve this error.
here is my code
from plotly.graph_objs import *
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly.offline.offline import _plot_html
init_notebook_mode(connected=True)
for col in state_df.columns:
state_df[col] = state_df[col].astype(str)
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)']]
state_df['text'] = state_df['StateCode'] + '<br>' +'TotalPlans '+state_df['TotalPlans']
data = [ dict(
type='choropleth',
colorscale = scl,
autocolorscale = False,
locations = state_df['StateCode'],
z = state_df['TotalPlans'].astype(float),
locationmode = 'USA-states',
text = state_df['text'],
marker = dict(
line = dict (
color = 'rgb(255,255,255)',
width = 2
)
),
colorbar = dict(
title = "Millions USD"
)
) ]
layout = dict(
title = 'Plan by States',
geo = dict(
scope='usa',
projection=dict( type='albers usa' ),
showlakes = True,
lakecolor = 'rgb(255, 255, 255)',
),
)
fig = dict(data=data, layout=layout)
plotly.offline.iplot(fig)
You are passing a dictionary to iplot which in contradiction to the documentation can handle only Figure objects and not dictionaries.
Try
fig = Figure(data=[data], layout=layout)
and it should work.

Categories

Resources