Problem summary
Whenever I try to create a plot with plotly express 5.18.0 containing a subplot and axes labels that are not numbers, I only get labels for the first subplot subsequent subplots show empty axis labels.
How can I ensure that all subplots show their respective axes labels, even if they contain strings?
Example data
import numpy as np
import pandas as pd
import plotly.express as px
N = 100
food = ["Dim sum", "Noodles", "Burger", "Pizza", "Pancake"]
drink = ["Beer", "Wine", "Soda", "Water", "Fruit juice", "Coffee", "Tea"]
df = pd.DataFrame(
{
"age": np.random.randint(8, 99, N),
"favourite_food": np.random.choice(food, N, replace=True),
"favourite_drink": np.random.choice(drink, N, replace=True),
"max_running_speed": np.random.random(N)*20,
"number_of_bicycles": np.random.randint(0, 5, N)
}
)
df.age.replace({range(0, 19): "Kid", range(19, 100): "Adult"}, inplace=True)
Random 5 rows:
age | favourite_food | favourite_drink | max_running_speed | number_of_bicycles | |
---|---|---|---|---|---|
0 | Adult | Dim sum | Wine | 8.57536 | 2 |
65 | Kid | Pizza | Water | 9.45698 | 1 |
57 | Kid | Pancake | Beer | 11.1445 | 0 |
84 | Adult | Dim sum | Soda | 8.80699 | 0 |
45 | Adult | Pizza | Fruit juice | 17.7258 | 4 |
Demonstration of problem
If I now create a figure with two subplots:
- First subplot contains the distribution of the max. running speed (a number)
- Second subplot contains the distribution of the number of bicycles (a number)
For convenience I use the facet_col
argument in combination with the wide-form support of plotly express and the formatting updates I found in this related Q&A):
px.histogram(
df,
x=["max_running_speed", "number_of_bicycles"],
facet_col="variable",
color="age",
barmode="group",
histnorm="percent",
text_auto=".2r",
).update_xaxes(matches=None, showticklabels=True).update_yaxes(matches=None, showticklabels=True)
All works as it should ✅: I get separate ranges x- and y-axes and I get separate labels on the x-axes.
Now I do the same, but for the columns with text data:
px.histogram(
df,
x=["favourite_food", "favourite_drink"],
facet_col="variable",
color="age",
barmode="group",
histnorm="percent",
text_auto=".2r",
).update_xaxes(matches=None, showticklabels=True).update_yaxes(matches=None, showticklabels=True)
Now there's a problem ❌: The x-axis of the right plot does not show the names of the favourite drinks.
What I've tried
I checked the underlying data JSON object, as I noticed that when I hover over the bars of the right plot, the "value" field is empty:
But when I inspect the JSON object in the .data
key of the figure, I see that x-values are present for both histograms:
One of the plotly contributors suggested I use the
.update_traces(bingroup=None)
on my figure. This indeed shows the missing categories on the right plot and is a viable workaround for now.