Plotly: How to use both dollar signs and linebreaks in annotations? - python

Not sure if I'm missing something obvious here but when I'm inserting a break (<br>) into my text with annotations it just seems to ignore it. I've tried fig.add_annotations but the same thing happens.
Do you know why this isn't working?
import pandas as pd
import plotly.graph_objects as go
import numpy as np
df = pd.DataFrame({"Growth_Type": ["Growing Fast", "Growing", "Stable", "Dropping", "Dropping Fast"],
"Accounts": [407,1275,3785,1467,623],
"Gain_Share": [1.20,8.1,34.4,6.5,0.4],
"Keep_Share": [16.5, 101.2, 306.3, 107.2, 27.7]})
df2 = pd.concat([pd.DataFrame({"Growth_Type":df["Growth_Type"],
"Opportunity_Type": np.repeat("Gain Share", 5),
"Wallet_Share": df["Gain_Share"]}),
pd.DataFrame({"Growth_Type":df["Growth_Type"],
"Opportunity_Type": np.repeat("Keep Share", 5),
"Wallet_Share": df["Keep_Share"]})])
fig = go.Figure()
fig.add_trace(go.Bar(x = df2["Wallet_Share"],
y = df2["Growth_Type"],
orientation = "h"
))
fig.update_layout(font = dict(size = 12, color = "#A6ACAF"),
xaxis_tickprefix = "$",
plot_bgcolor = "white",
barmode = "stack",
margin = dict(l = 150,
r = 250,
b = 100,
t = 100),
annotations = [dict(text = 'Dropping presents a gain share<br>opportunity of $6.5 mill and a<br>keep share opportunity of $34.4 mill',
xref = "x",
yref = "y",
x = 360,
y = "Dropping",
showarrow = False,
yanchor = "bottom")]
)
fig.show()

It's not the linebreaks that are causing the trouble here; it is the dollar sign.
But you can use the printable ASCII character '$'to get what you want instead:
text = 'Dropping presents a gain share<br>opportunity of '+ '$'+ '6.5 mill and a<br>keep share opportunity of ' + '$'+ '34.4 mill'
Plot:
Complete code:
import pandas as pd
import plotly.graph_objects as go
import numpy as np
df = pd.DataFrame({"Growth_Type": ["Growing Fast", "Growing", "Stable", "Dropping", "Dropping Fast"],
"Accounts": [407,1275,3785,1467,623],
"Gain_Share": [1.20,8.1,34.4,6.5,0.4],
"Keep_Share": [16.5, 101.2, 306.3, 107.2, 27.7]})
df2 = pd.concat([pd.DataFrame({"Growth_Type":df["Growth_Type"],
"Opportunity_Type": np.repeat("Gain Share", 5),
"Wallet_Share": df["Gain_Share"]}),
pd.DataFrame({"Growth_Type":df["Growth_Type"],
"Opportunity_Type": np.repeat("Keep Share", 5),
"Wallet_Share": df["Keep_Share"]})])
fig = go.Figure()
fig.add_trace(go.Bar(x = df2["Wallet_Share"],
y = df2["Growth_Type"],
orientation = "h"
))
fig.update_layout(font = dict(size = 12, color = "#A6ACAF"),
xaxis_tickprefix = "$",
plot_bgcolor = "white",
barmode = "stack",
margin = dict(l = 150,
r = 250,
b = 100,
t = 100),
annotations = [dict(text = 'Dropping presents a gain share<br>opportunity of '+ '$'+ '6.5 mill and a<br>keep share opportunity of ' + '$'+ '34.4 mill',
#annotations = [dict(text = '$',
xref = "x",
yref = "y",
x = 360,
y = "Dropping",
showarrow = False,
yanchor = "bottom")]
)
fig.show()

Related

Bokeh how to get GlyphRenderer for Annotation

With Bokeh, how do I get a handle to the Renderer (or GlyphRenderer) for an Annotation? Is this possible?
I would like to be able to toggle a Band (which is an Annotation) on and off with an interactive legend, so I need to be able to pass a list of Renderers to the LegendItem constructor.
This code:
maxline = fig.line(x='Date', y=stn_max, line_width=0.5, legend=stn_max, name="{}_line".format(stn_max), color=stn_color, alpha=0.75, source=source)
minline = fig.line(x='Date', y=stn_min, line_width=0.5, legend=stn_min, name="{}_line".format(stn_min), color=stn_color, alpha=0.75, source=source)
band = bkm.Band(base='Date', lower=stn_min, upper=stn_max, fill_alpha=0.50, line_width=0.5, fill_color=stn_color, source=source)
bkm.LegendItem(label=stn, renderers=[maxline, minline, band])
Produces this error
...
ValueError: expected an element of List(Instance(GlyphRenderer)), got seq with invalid items [Band(id='1091', ...)]
For LegendItem only instances of GlyphRenderer can be passed to its renderers attribute and Band is not based on GlyphRenderer so it gives error. In the code below the Band visibility is being toggled by means of a callback:
from bokeh.plotting import figure, show
from bokeh.models import Band, ColumnDataSource, Legend, LegendItem, CustomJS
import pandas as pd
import numpy as np
x = np.random.random(2500) * 140 - 20
y = np.random.normal(size = 2500) * 2 + 5
df = pd.DataFrame(data = dict(x = x, y = y)).sort_values(by = "x")
sem = lambda x: x.std() / np.sqrt(x.size)
df2 = df.y.rolling(window = 100).agg({"y_mean": np.mean, "y_std": np.std, "y_sem": sem})
df2 = df2.fillna(method = 'bfill')
df = pd.concat([df, df2], axis = 1)
df['lower'] = df.y_mean - df.y_std
df['upper'] = df.y_mean + df.y_std
source = ColumnDataSource(df.reset_index())
p = figure(tools = "pan,wheel_zoom,box_zoom,reset,save")
scatter = p.scatter(x = 'x', y = 'y', line_color = None, fill_alpha = 0.3, size = 5, source = source)
band = Band(base = 'x', lower = 'lower', upper = 'upper', source = source)
p.add_layout(band)
p.title.text = "Rolling Standard Deviation"
p.xaxis.axis_label = 'X'
p.yaxis.axis_label = 'Y'
callback = CustomJS(args = dict(band = band), code = """
if (band.visible == false)
band.visible = true;
else
band.visible = false; """)
legend = Legend(items = [ LegendItem(label = "x", renderers = [scatter, band.source.selection_policy]) ])
legend.click_policy = 'hide'
scatter.js_on_change('visible', callback)
p.add_layout(legend)
show(p)
Result:

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:

Python Plotly Error

It seems that the example code on the plotly website for choropleth maps is out of date and no longer works.
The error I'm getting is:
PlotlyError: Invalid 'figure_or_data' argument. Plotly will not be able to properly parse the resulting JSON. If you want to send this 'figure_or_data' to Plotly anyway (not recommended), you can set 'validate=False' as a plot option.
Here's why you're seeing this error:
The entry at index, '0', is invalid because it does not contain a valid 'type' key-value. This is required for valid 'Data' lists.
Path To Error:
['data'][0]
The code that I'm trying to run is shown below. It is copied as-is from the plotly website. Anyone have any ideas as to how I can fix it?
import plotly.plotly as py
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv')
for col in df.columns:
df[col] = 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)']]
df['text'] = df['state'] + '<br>' +\
'Beef '+df['beef']+' Dairy '+df['dairy']+'<br>'+\
'Fruits '+df['total fruits']+' Veggies ' + df['total veggies']+'<br>'+\
'Wheat '+df['wheat']+' Corn '+df['corn']
data = [ dict(
type='choropleth',
colorscale = scl,
autocolorscale = False,
locations = df['code'],
z = df['total exports'].astype(float),
locationmode = 'USA-states',
text = df['text'],
marker = dict(
line = dict (
color = 'rgb(255,255,255)',
width = 2
)
),
colorbar = dict(
title = "Millions USD"
)
) ]
layout = dict(
title = '2011 US Agriculture Exports by State<br>(Hover for breakdown)',
geo = dict(
scope='usa',
projection=dict( type='albers usa' ),
showlakes = True,
lakecolor = 'rgb(255, 255, 255)',
),
)
fig = dict(data=data, layout=layout)
url = py.plot(fig, filename='d3-cloropleth-map')
fig should be of the Figure type. Use the Choropleth graph object:
import plotly.graph_objs as go
...
data = [go.Choropleth(
colorscale = scl,
autocolorscale = False,
locations = df['code'],
z = df['total exports'].astype(float),
locationmode = 'USA-states',
text = df['text'],
marker = dict(
line = dict(
color = 'rgb(255,255,255)',
width = 2)),
colorbar = dict(
title = "Millions USD")
)]
...
fig = go.Figure(data=data, layout=layout)
...

Python - plotly hover icon not working

As far as I'm aware, I've copied the documentation exactly. I basically used the documentation code and tweaked it for my purposes. But when I run this bit of code, no hover feature with text appears on my plot.
#Initialize df
aviation_data = pd.DataFrame(columns=["Latitude","Longitude","Fatalities"])
aviation_data["Latitude"] = [40.53666,60.94444]
aviation_data["Longitude"] = [-81.955833,-159.620834]
aviation_data["Fatalities"] = [True,False]
#Initialize colorscale
scl = [[0,"rgb(216,15,15)"],[1,"rgb(5,10,172)"]]
#Initialize text data
text_df = "Fatal: " + aviation_data["Fatalities"].apply(lambda x: str(np.bool(x))) + '<br>' + \
"Latitude: " + aviation_data["Latitude"].apply(lambda x: str(x)) + '<br>' + \
"Longitude" + aviation_data["Longitude"].apply(lambda x: str(x))
#Initialize data
data = [ dict(
type = 'scattergeo',
locationmode = 'USA-states',
lon = aviation_data["Longitude"],
lat = aviation_data["Latitude"],
text = text_df,
mode = 'markers',
marker = dict(
size = 5,
opacity = 0.5,
reversescale=True,
autocolorscale=False,
symbol = 'circle',
line = dict(
width=1,
color='rgba(102, 102, 102)'
),
colorscale = scl,
cmin = 0,
color = aviation_data["Fatalities"].astype(int),
cmax = 1
))]
#Initialize layout
layout = dict(
title ='Aviation Incidents for the Years 2014-2016<br>\
(red indicates fatal incident, blue indicates non-fatal)',
geo = dict(
scope='usa',
projection=dict(type='albers usa'),
showland = True,
landcolor = "rgb(206, 206, 206)",
countrywidth = 0.5,
subunitwidth = 0.5
),
)
#Plot
fig = dict(data=data,layout=layout)
iplot(fig,validate=False)
Anyone know why my hover text isn't showing up?
In the last line of code you need to call this:
plotly.offline.plot(fig, validate=False)
Instead of:
iplot(fig, validate=False)
Also do not forget import plotly:
import plotly
Hope this will help

Python Plotly - Align Y Axis for Scatter and Bar

I'm trying to create a plotly graph with a Scatter and Graph elements. It all goes nicely, but one issue - the two Y axis don't align around 0.
I have tried playing with different attributes, such as 'mirror' and tick0, I also tried following the examples on plotly's site, but it's mostly multiple y-axis with the same graph type.
What can I do to fix this?
import utils
import pandas as pd
import plotly.plotly as py
import plotly.graph_objs as go
import plotly
pd_data ['dt'] = ... dates
pd_data['price'] = ... prices
pd_data['car'] = ... cars
price = go.Scatter(
x = pd_data['dt'],
y = pd_data['price'],
mode = 'lines',
name = 'Price',
xaxis = 'x',
yaxis='y1',
marker = dict(
color = utils.prep_color_string('orange'),
),
line = dict(
width = utils.line_width,
),
)
car = go.Bar(
x = pd_data['dt'],
y = pd_data['car'],
#mode = 'lines',
name = 'Cars',
xaxis = 'x',
yaxis='y2',
marker = dict(
color = utils.prep_color_string('light_green'),
),
#line = dict(
# width = utils.line_width,
#),
)
data = [price, car]
layout = dict(
title = 'Price/Car',
geo = dict(
showframe = True,
showcoastlines = True,
projection = dict(
type = 'Mercator'
)
),
yaxis=dict(
title = 'Price',
tickprefix = "$",
overlaying='y2',
anchor = 'x'
),
yaxis2=dict(
title = 'Car',
dtick = 1,
#tickprefix = "",
side = 'right',
anchor = 'x',
),
)
fig = dict( data=data, layout=layout)
div = plotly.offline.plot( fig, validate=False, output_type = 'file',filename='graph.html' ,auto_open = False)
I have been struggling with this as well. Exact same problem, but I am using R. The way I figured around it was to use the rangemode="tozero" for both the yaxis and yaxis2 layouts.
I think in your case, it would look like this:
layout = dict(
title = 'Price/Car',
geo = dict(
showframe = True,
showcoastlines = True,
projection = dict(
type = 'Mercator'
)
),
yaxis=dict(
title = 'Price',
tickprefix = "$",
overlaying='y2',
anchor = 'x',
rangemode='tozero'
),
yaxis2=dict(
title = 'Car',
dtick = 1,
#tickprefix = "",
side = 'right',
anchor = 'x',
rangemode = 'tozero'
),
)
Let me know if that works for you.

Categories