繁体   English   中英

在 go.Pie 子图中更改调色板时保持相同的图例

[英]Keeping the same legend while changing the palette in go.Pie subplot

我正在尝试用两个馅饼制作一个subplot ,但在更改palette时我无法为它们保留相同的legend (尽管它适用于 plotly 默认palette

我正在使用两个数据框。 它们是用value_counts制作的,因此是排序的。

yearly = pd.DataFrame(data={'index': ['A', 'B','C','D'], 'count': [3000, 2000,1000,50]})
monthly = pd.DataFrame(data={'index': ['B', 'A','C','D'], 'count': [250, 200,80,10]})

两个 dfs 中的index AB是相反的。

那么如果我这样做:

fig = make_subplots(rows=1, cols=2, specs=[[{"type": "pie"}, {"type": "pie"}]])

fig.add_trace(go.Pie(
     values=monthly['count'],
     labels=monthly['index'].astype(str),
     title='Monthly'), 
     row=1, col=1)

fig.add_trace(go.Pie(
     values=yearly['count'],
     labels=yearly['index'].astype(str),
     title="yearly",),
    row=1, col=2)

fig.update_layout(legend=dict(x=0.4))
                  
fig.update_traces(textposition='inside', textinfo='percent+label')                  
fig.show()

它工作正常,我对两个图表都有相同的legend (即两个图表上的每个索引都具有相同的颜色)

使用默认调色板的结果 = 我想要的

但是,如果我尝试更改palette并将fig.update_trace更改为此

fig.update_traces(textposition='inside', textinfo='percent+label'
                  ,marker=dict(colors=["#93C572","#CD5C5C","#F49D37","#3C6C82"]))

它不起作用了。 AB在两个图表上的color不同, legend仅适用于第一个图表。

自定义调色板的结果 = 未共享图例

我不明白为什么。 否则,我将最终对df进行排序,以便索引始终处于相同的顺序(A、B、C、D),但我确信有更优雅的方法。

我已经尝试了这个线程Map colors 的解决方案到 plotly go 中的标签。饼图但它没有用。

我不确定你打算做什么,因为没有包含特定图例的图像,但我认为如果每个子图单元都有自己的图例,这个问题就会得到解决。 您想要的子图是一行两列,但图例出现在上方和下方。 这似乎是饼图子图的默认行为。 为了改善这一点,我将其设为 2 行和 1 列。 另外,我打开了图例之间的空间,使它们与子图对齐。

fig = make_subplots(rows=2, cols=1, specs=[[{"type": "pie"}], [{"type": "pie"}]])

fig.add_trace(go.Pie(
     values=monthly['count'],
     labels=monthly['index'].astype(str),
    title='Monthly', legendgroup='gr1'),
     row=1, col=1)

fig.add_trace(go.Pie(
     values=yearly['count'],
     labels=yearly['index'].astype(str),
     title="yearly", legendgroup='gr2'),
    row=2, col=1)

# fig.update_traces(textposition='inside', textinfo='percent+label'
#                   ,marker=dict(colors=["#93C572","#CD5C5C","#F49D37","#3C6C82"]))

fig.update_traces(textposition='inside', textinfo='percent+label')
fig.update_layout(height=600, width=500, legend_tracegroupgap=180)
fig.show()

在此处输入图像描述

在我的回复中,我将饼图垂直对齐,因为如果饼图水平对齐,则会出现下图。

fig.update_layout(autosize=False, width=450, legend=dict(yanchor='top', y=0.85, tracegroupgap=35))

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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