Skip to content

Merge recent docs updates #4589

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 23 commits into from
Apr 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
dccbdf8
proposed addition of a df.agg stacked go.bar example
rl-utility-man Mar 14, 2024
b8a198d
Update bar-charts.md
rl-utility-man Mar 14, 2024
32a2c0c
Update bar-charts.md
rl-utility-man Mar 14, 2024
5e89427
Update doc/python/bar-charts.md
archmoj Mar 22, 2024
d628817
Update hover-text-and-formatting.md
rl-utility-man Mar 25, 2024
eca3711
Update doc/python/bar-charts.md
LiamConnors Apr 10, 2024
c3fbb64
Update doc/python/bar-charts.md
LiamConnors Apr 10, 2024
4fc1402
Merge pull request #4577 from plotly/make-docs-updates-5-21-live
LiamConnors Apr 17, 2024
666b601
Merge branch 'doc-prod' into patch-4
LiamConnors Apr 17, 2024
95cb360
Merge pull request #4546 from rl-utility-man/patch-4
LiamConnors Apr 18, 2024
b786d9c
fix: Code block not rendering
ShivMunagala Apr 18, 2024
788013d
Merge pull request #4579 from ShivMunagala/patch-1
LiamConnors Apr 18, 2024
1e63ed4
Update doc/python/hover-text-and-formatting.md
LiamConnors Apr 22, 2024
70655ea
Update doc/python/hover-text-and-formatting.md
LiamConnors Apr 22, 2024
02cf1b1
Update doc/python/hover-text-and-formatting.md
LiamConnors Apr 22, 2024
7c4b954
Update doc/python/hover-text-and-formatting.md
LiamConnors Apr 22, 2024
fb060bd
Update doc/python/hover-text-and-formatting.md
LiamConnors Apr 22, 2024
b06b80b
Update doc/python/hover-text-and-formatting.md
LiamConnors Apr 22, 2024
2e34c04
Merge branch 'doc-prod' into patch-5
LiamConnors Apr 22, 2024
eba6910
Update doc/python/hover-text-and-formatting.md
LiamConnors Apr 23, 2024
217ed66
Update doc/python/hover-text-and-formatting.md
LiamConnors Apr 24, 2024
2fa17d9
Merge pull request #4557 from rl-utility-man/patch-5
LiamConnors Apr 24, 2024
6ed004b
Merge branch 'master' into recent-docs-updates
LiamConnors Apr 25, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions doc/python/bar-charts.md
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,56 @@ fig.update_layout(barmode='stack')
fig.show()
```

### Stacked Bar Chart From Aggregating a DataFrame

Stacked bar charts are a powerful way to present results summarizing categories generated using the Pandas aggregate commands. `pandas.DataFrame.agg` produces a wide data set format incompatible with `px.bar`. Transposing and updating the indexes to achieve `px.bar` compatibility is a somewhat involved option. Here is one straightforward alternative, which presents the aggregated data as a stacked bar using plotly.graph_objects.

```python
from plotly import graph_objects as go
import pandas as pd

# Get one year of gapminder data
url = 'https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv'
df = pd.read_csv(url)
df = df[df['year']==2007]
df["gdp"]=df["pop"]*df['gdpPercap']


# Build the summary of interest
df_summarized = df.groupby("continent", observed=True).agg("sum").reset_index()

df_summarized["percent of world population"]=100*df_summarized["pop"]/df_summarized["pop"].sum()
df_summarized["percent of world GDP"]=100*df_summarized["gdp"]/df_summarized["gdp"].sum()


df = df_summarized[["continent",
"percent of world population",
"percent of world GDP",
]]

# We now have a wide data frame, but it's in the opposite orientation from the one that px is designed to deal with.
# Transposing it and rebuilding the indexes is an option, but iterating through the DF using graph objects is more succinct.

fig=go.Figure()
for category in df_summarized["continent"].values:
fig.add_trace(go.Bar(
x=df.columns[1:],
# We need to get a pandas series that contains just the values to graph;
# We do so by selecting the right row, selecting the right columns
# and then transposing and using iloc to convert to a series
# Here, we assume that the bar element category variable is in column 0
y=list(df.loc[df["continent"]==category][list(df.columns[1:])].transpose().iloc[:,0]),
name=str(category)


)
)
fig.update_layout(barmode="stack")

fig.show()
```


### Bar Chart with Hover Text

```python
Expand Down
90 changes: 76 additions & 14 deletions doc/python/hover-text-and-formatting.md
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,58 @@ print("user_defined hovertemplate:", fig.data[0].hovertemplate)
fig.show()
```

### Specifying the formatting and labeling of custom fields in a Plotly Express figure using a hovertemplate

This example adds custom fields to a Plotly Express figure using the custom_data parameter and then adds a hover template that applies d3 formats to each element of the customdata[n] array and uses HTML to customize the fonts and spacing.

```python
# %%
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import math
import numpy as np

data = px.data.gapminder()
df = data[data['year']==2007]
df = df.sort_values(['continent', 'country'])

df.rename(columns={"gdpPercap":'GDP per capita', "lifeExp":'Life Expectancy (years)'}, inplace=True)

fig=px.scatter(df,
x='GDP per capita',
y='Life Expectancy (years)',
color='continent',
size=np.sqrt(df['pop']),
# Specifying data to make available to the hovertemplate
# The px custom_data parameter has an underscore, while the analogous graph objects customdata parameter has no underscore.
# The px custom_data parameter is a list of column names in the data frame, while the graph objects customdata parameter expects a data frame or a numpy array.
custom_data=['country', 'continent', 'pop'],
)

# Plotly express does not have a hovertemplate parameter in the graph creation function, so we apply the template with update_traces
fig.update_traces(
hovertemplate =
"<b>%{customdata[0]}</b><br>" +
"<b>%{customdata[1]}</b><br><br>" +
"GDP per Capita: %{x:$,.0f}<br>" +
"Life Expectation: %{y:.0f}<br>" +
"Population: %{customdata[2]:,.0f}" +
"<extra></extra>",
mode='markers',
marker={'sizemode':'area',
'sizeref':10},
)

fig.update_layout(
xaxis={
'type':'log'},
)

fig.show()
```


### Hover Templates with Mixtures of Period data

*New in v5.0*
Expand Down Expand Up @@ -319,7 +371,7 @@ fig.show()

### Advanced Hover Template

The following example shows how to format a hover template.
This produces the same graphic as in "Specifying the formatting and labeling of custom fields in a Plotly Express figure using a hovertemplate" above, but does so with the `customdata` and `text` parameters of `graph_objects`. It shows how to specify columns from a dataframe to include in the customdata array using the df[["col_i", "col_j"]] subsetting notation. It then references those variables using e.g. %{customdata[0]} in the hovertemplate. It includes comments about major differences between the parameters used by `graph_objects` and `plotly.express`.

```python
import plotly.graph_objects as go
Expand All @@ -343,21 +395,31 @@ continent_data = {continent:df_2007.query("continent == '%s'" %continent)

fig = go.Figure()

for continent_name, continent in continent_data.items():
fig.add_trace(go.Scatter(
x=continent['gdpPercap'],
y=continent['lifeExp'],
name=continent_name,
text=continent['continent'],
hovertemplate=
"<b>%{text}</b><br><br>" +
"GDP per Capita: %{x:$,.0f}<br>" +
"Life Expectation: %{y:.0%}<br>" +
"Population: %{marker.size:,}" +
"<extra></extra>",
marker_size=continent['size'],
for continent_name, df in continent_data.items():
fig.add_trace(
go.Scatter(
x=df['gdpPercap'],
y=df['lifeExp'],
marker_size=df['size'],
name=continent_name,

# The next three parameters specify the hover text
# Text supports just one customized field per trace
# and is implemented here with text=df['continent'],
# Custom data supports multiple fields through numeric indices in the hovertemplate
# In we weren't using the text parameter in our example,
# we could instead add continent as a third customdata field.
customdata=df[['country','pop']],
hovertemplate=
"<b>%{customdata[0]}</b><br>" +
"<b>%{text}</b><br><br>" +
"GDP per Capita: %{x:$,.0f}<br>" +
"Life Expectancy: %{y:.0f}<br>" +
"Population: %{customdata[1]:,.0f}" +
"<extra></extra>",
))


fig.update_traces(
mode='markers',
marker={'sizemode':'area',
Expand Down