简体   繁体   中英

How to make plotly bar subplot show colors for stacks, not for traces

I want to color the bar stacks according to a column in each dataframe called 'types', but I do not know where to set this argument (in the Plotly Express API there's the color parameter).

Weird thing is that Plotly is already marking the bar with the stacks, but [as it should] coloring all of them the same way, according to the trace:

from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(rows=1, cols=2)
fig.add_trace(go.Bar(x = grouped_A["Working Days"], y = grouped_A["Total"], 1, 1)
fig.add_trace(go.Bar(x = grouped_B["Working Days"], y = grouped_B["Total"], 1, 2)

fig.show()

在此处输入图片说明

You can use the Plotly Express API to create your graphs and then add those to the subplots.

from plotly.subplots import make_subplots
import plotly.graph_objects as go
import plotly.express as px

fig = make_subplots(rows=1, cols=2)
bar1 = px.bar(grouped_A, x = "Working Days", y = "Total", color="types")
bar2 = px.bar(grouped_B, x = "Working Days", y = "Total", color="types")

for trace in bar1.data:
    fig.add_trace(trace, 1, 1)
for trace in bar2.data:
    fig.add_trace(trace, 1, 2)


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

Additionally if you want the 'types' to have the same colors in each subplot, you can add a color mapping as a parameter to px.bar()

color_discrete_map=color_map

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM