如何使绘图条形子图显示堆栈的颜色,而不是迹线的颜色

Luc*_*ias 0 python plot plotly

我想根据每个数据帧中名为“types”的列为条形堆栈着色,但我不知道在哪里设置此参数(在 Plotly Express API 中有该参数color)。

奇怪的是,Plotly 已经用堆栈标记了条形图,但根据跟踪,[理所应当]以相同的方式对所有条形图着色:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

use*_*088 6

您可以使用 Plotly Express API 创建图表,然后将其添加到子图中。

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()
Run Code Online (Sandbox Code Playgroud)

此外,如果您希望“类型”在每个子图中具有相同的颜色,您可以将颜色映射作为参数添加到 px.bar()

color_discrete_map=color_map
Run Code Online (Sandbox Code Playgroud)