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

时间:2020-03-11 10:28:22

标签: python plot plotly

我想根据每个数据帧中称为“类型”的一列为条形烟囱着色,但是我不知道在何处设置此参数(在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()

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以使用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()

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

color_discrete_map=color_map