Reputation: 189
Assume we're using the plotly px.data.iris() dataset to generate a stacked bar chart. This is pretty straight-forward using plotly express:
import plotly.express as px
df = px.data.iris()
df = df[["sepal_width", "sepal_length", "species"]]
df = df[(df["sepal_width"] > 2.7) & (df["sepal_width"] < 3.3)]
df
sepal_width sepal_length species
0 3.5 5.1 setosa
1 3.0 4.9 setosa
2 3.2 4.7 setosa
3 3.1 4.6 setosa
4 3.6 5.0 setosa
...
141 3.1 6.9 virginica
143 3.2 6.8 virginica
145 3.0 6.7 virginica
147 3.0 6.5 virginica
149 3.0 5.9 virginica
The bar chart should be "stacked", using the species column:
fig = px.bar(df, x="sepal_width", y="sepal_length", color="species")
fig.show()
And will look something like this:
My problem is that I need to include this as a subplot, with several other subplots:
from plotly.subplots import make_subplots
bigFig = make_subplots(
rows=2, cols=2,
specs = [
[{"type": "pie"}, {"type": "pie"}],
[{"type": "bar"}, {"type": "bar"}],
],
subplot_titles=("pie1", "pie2", "bar1", "bar2")
)
I can't (or, can't figure out how to) use a plotly express bar chart in the subplot, and I can't figure out how to translate the stacked part -- color="species"
-- into a graph_objects chart in such a way to make the plot *look as pretty as the plotly express version, and visually differentiate the species values.
My attempt at a "go" bar chart is:
import plotly.graph_objects as go
bar_trace = go.Figure(go.Bar(
x=df['sepal_width'], y=df['sepal_length'] # how to indicate the base/color selector
)
bigFig.add_trace(bar_trace, row=2, col=2)
This results in a bar chart that looks something like:
It will appear in the desired subplot of bigFig
. While it is stacking the sepal_length
values (good), I need for the stacking to be "based" on the Species values, and be visually apparent.
When I tried to declare the base:
import plotly.graph_objects as go
fig = go.Figure(go.Bar(x=df["sepal_width"], y=df["sepal_length"], base=df["species"]))
fig.update_layout(barmode="stack")
fig.show()
The result doesn't match the expected output, and the apparent stacks are all the same color:
I found this solution and grabbed the barmode="stack"
idea from it. But, it did not help my situation and I can't figure out why.
So, please help me get the pretty version into a subplot. I must be missing something fundamental, but I've been banging my head on this for a while. TIA!
Upvotes: 0
Views: 46