Plotly: How to add elements to hover_data using plotly.express piechart? - python

I am playing with examples from plotly.express piechart help page and trying to add an extra element iso_num to the hover_data property (iso_num is an int64 column in the gapminder dataframe)
import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Americas'")
fig = px.pie(df, values='pop', names='country',
title='Population of American continent',
hover_data=['lifeExp','iso_num'], labels={'lifeExp':'life expectancy','iso_num':'iso num'
})
fig.update_traces(textposition='inside', textinfo='percent+label')
fig.show()
Hovering over the slice of the pie chart then gives this:
where iso num value is %{customdata[1]} instead of the numeric value from the column.
What am I missing?
Thanks!

I found a way to do it with Plotly Express Pie chart as well. You can use update_traces to define hover_template. It seems there is an issue with splitting on multiple values for hover_data/custom_data and all values are present at 0 index only i.e. both values are at customdata[0].
import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Americas'")
fig = px.pie(df, values='pop', names='country',
title='Population of American continent',
custom_data=['lifeExp','iso_num'], labels={'lifeExp':'life expectancy','iso_num':'iso num'
})
fig.update_traces(textposition='inside', textinfo='percent+label',\
hovertemplate = "Country:%{label}: <br>Population: %{value} </br>(life expentancy, iso num) : %{customdata}"
)
fig.show()
On hover:

This seems to be a relic from back when it was stated that
Oh pie hover is a big mess
Which since seems to be have been resolved. But perhaps not for px.pie()?
I've tried numerous approaches, but I'm only able to get the customdata + hovertemplate approach to work for go.Pie and not for px.Pie. Here's a demonstration on how assigning values to customdata will make any variable otherwise not assigned to go.Pie() available for a custom hovertamplate:
Plot:
Code:
import plotly.graph_objects as go
import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Americas'")
fig = go.Figure(go.Pie(
name = "",
values = df['pop'],
labels = df['country'],
customdata=df['iso_num'],
hovertemplate = "Country:%{label}: <br>Population: %{value} </br> iso num:%{customdata}"
))
fig.show()

Related

how to control max length of colum names graph in plotly dash

i have a code like that
import plotly.express as px
df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")
fig = px.bar(df, y='pop', x='country', text='pop')
fig.update_traces(texttemplate='%{text:.2s}', textposition='outside')
fig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide')
fig.show()
and it builds me this diagram
how to make max length on colums name?
I think there is a very similar question & answer here. Adapted to your case, you could chose to keep only the first n letters of the column name. It would look like the following:
import plotly.express as px
# Data
df = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")
# Figure
fig = px.bar(df, y='pop', x='country', text='pop')
fig.update_traces(texttemplate='%{text:.2s}', textposition='outside')
fig.update_layout(uniformtext_minsize=8, uniformtext_mode='hide')
# The modification: overwrite tick labels
# Choose the number of letters to keep
n = 7
fig.update_layout(
xaxis = {
'tickmode': 'array',
'tickvals': df.country.unique().tolist(),
'ticktext': [i[:n] for i in df.country.unique().tolist()],
}
)
fig.show()
For n=7 it produces:

Plotly: Hide date in axis ticks but show in hoverlabel title created with `x unified`

In the axis ticklabels, I want to show only the month and the year (grouped), like this -
But that also means I have to sacrifice on the day of the date (1-31) in the hoverlabel title. Is there a way I can hide the day part of the date on the axis (with grouped years and short month) and yet see it on the hoverlabel title? Something like this but without the 01s before each month on the axis.
Here's the code to reproduce the graph-
import plotly.express as px
df = px.data.stocks()
fig = px.line(df, x='date', y=['GOOG','AAPL'])
fig.update_layout(hovermode='x unified', xaxis_title=None, yaxis_title=None, xaxis_tickformat='%d%b\n%Y',
hoverlabel=dict(namelength=0))
fig.update_traces(hovertemplate=None)
# fig.update_traces(hovertemplate='%{x|%d%b,%Y} value: %{y:.2f}')
You can modify the parameter xaxis_hoverformat in the update_layout method. In this case, you don't need to use a hovertemplate.
import plotly.express as px
df = px.data.stocks()
fig = px.line(df, x='date', y=['GOOG','AAPL'])
fig.update_layout(
hovermode='x unified',
xaxis_title=None,
yaxis_title=None,
xaxis_tickformat='%b\n%Y',
xaxis_hoverformat='%d%b,%Y',
hoverlabel=dict(namelength=0)
)
fig.update_traces(hovertemplate=None)
fig.show()

How to get standard notation (rather than scientific) when hovering over pie chart in Plotly

I have a pie chart that displays worldwide movie sales by rating. When I hover over the chart the woldwide sales are being displayed in scientific notation. How do I fix this so that worldwide sales are represented in standard notation instead? I would appreciate it if anyone has a solution to this in express or graph objects (or both).
Thank you.
# formatting and importing data
import pandas as pd
movie_dataframe = pd.read_csv("https://raw.githubusercontent.com/NicholasTuttle/public_datasets/main/movie_data.csv") # importing dataset to dataframe
movie_dataframe['worldwide_gross'] = movie_dataframe['worldwide_gross'].str.replace(',', '', regex=True) # removing commas from column
movie_dataframe['worldwide_gross'] = movie_dataframe['worldwide_gross'].str.replace('$', '' , regex=True ) # removing dollar signs from column
movie_dataframe['worldwide_gross'] = movie_dataframe['worldwide_gross'].astype(float)
# narrowing dataframe to specific columns
movies_df = movie_dataframe.loc[:, ['title', 'worldwide_gross', 'rating', 'rt_score', 'rt_freshness']]
# plotly express
import plotly.express as px
fig = px.pie(movies_df,
values= movies_df['worldwide_gross'],
names= movies_df['rating'],
)
fig.show()
# plotly graph objects
import plotly.graph_objects as go
fig = go.Figure(go.Pie(
values = movies_df['worldwide_gross'],
labels = movies_df['rating']
))
fig.show()
Have a look here: https://plotly.com/python/hover-text-and-formatting/#disabling-or-customizing-hover-of-columns-in-plotly-express
Basically you give a dictionary of row name and format string to hover_data. The formatting string follows the d3-format's syntax.
import plotly.express as px
fig = px.pie(
movies_df, values= movies_df['worldwide_gross'], names= movies_df['rating'],
hover_data={
"worldwide_gross": ':.d',
# "worldwide_gross": ':.2f', # float
}
)
fig.show()
For the graph object API you need to write an hover_template:
https://plotly.com/python/reference/pie/#pie-hovertemplate
import plotly.graph_objects as go
fig = go.Figure(go.Pie(
values = movies_df['worldwide_gross'],
labels = movies_df['rating'],
hovertemplate='Rating: %{label}<br />World wide gross: %{value:d}<extra></extra>'
))
fig.show()

How to use this kind of scientific notation tick in plotly?

I am using plotly with python and I am trying to use use these kinds of tick in X and Y axis:
10-3, 10-4, 10-5, and so on..
Any suggestions or recoomended reading?
I am obtaining this:
I was also in a search for this feature, and found the solution in this other answer:
https://stackoverflow.com/a/56742105/418875
You should set exponentformat to the power option. This will print the ticks as shown below:
I believe the closes you'll get is logartihmic axes:
import plotly.express as px
df = px.data.gapminder().query("year == 2007")
fig = px.scatter(df, x="gdpPercap", y="lifeExp", hover_name="country", log_x=True)
fig.show()
This has been bugging me for a while, here's the best solution I've found:
TLDR, you can use HTML formatting to make sure the exponent is a superscript and use array mode to pass strings for the tick labels to plotly.
import plotly.express as px
import numpy as np
df = px.data.gapminder().query("year == 2007")
fig = px.scatter(df, x="gdpPercap", y="lifeExp", hover_name="country", log_x=True)
tickvals = np.logspace(3,6, num=4)
print(tickvals)
def format_tick(n: float):
m, e = f"{n:.0e}".split("e")
e = int(e)
return f"{m} x 10<sup>{e}</sup>"
ticktext = [format_tick(t) for t in tickvals]
print(ticktext)
fig.update_layout(
xaxis = dict(
tickmode = 'array',
tickvals = tickvals,
ticktext = ticktext,
)
)
fig.show()

creating a Piechart in Plotly/Dash out of a Dataframe/Pivot Table

This is my code, as a quick explanation I am filtering my dataframe to select the correct KPI, in this case Operator Share, the correct country, which is prestored in the variable country and the year 2017.
Then I want to create a piechart that uses the KPIvalues of the different specifications. So Specifications should be the labels and KPI values the values.
df_plot_operator_share = df[df['Country'] == Country]
df_plot_operator_share = df.loc[(df['KPIname'].isin(['OperatorShare'])) & (df['YearNb']==2017)]
pv_operator_share = pd.pivot_table(
df_plot_operator_share,
index=['Specification'],
values=['KPIvalue'],
aggfunc=sum,
fill_value=0)
trace1 = go.Pie(
lables= pv_operator_share.index, values= pv_operator_share["KPIvalue"],
name='OperatorShare')
return {
'data': [trace1],
'layout':
go.Layout(
title='Country: {} Operator Share'.format(Country),
)
}
The Pivot has the Specifications has the headers and the KPIvalues as its values.
I want to have a pie chart that uses the Specifications as labels and the KPIvalues as values.
But for some reason it is not working.
You tried to call plotly?
For example:
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
trace1 = go.Pie(
labels = pv_operator_share.index,
values= pv_operator_share["KPIvalue"],
name='OperatorShare'
)
data = [trace1]
layout = go.Layout(
title='Country: {} Operator Share'.format(Country),
)
fig = go.Figure(data=data, layout=layout)
plotly.offline.plot(fig, filename='Plot.html')
import plotly.express as px
fig = px.pie(df, values='numeric_value', names='column_name', title='Your title')
fig.show()

Categories