如何在 Plotly 中的两个子图之间共享图例颜色

How to share legend colors between two subplots in Plotly

我试图让两个子图共享相同的颜色模式以便于可视化。两个图都使用相同的变量来显示内容。当前图例显示为饼图的一部分。

我一直在努力寻找答案,但似乎无法弄清楚。

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

subfig = make_subplots(
    rows=1, cols=2,
    column_widths=[10,10],
    row_heights=[10],
    subplot_titles=("Enrollment by Percentage", "Enrollment by Status"),
    specs=[[{"type": "pie"}, {"type": "bar"}]])

cols = ['Baseline Failure', 'Exited Study', 'Screen Failure', 'Enrolled', 'Completed Study']
count = [146, 33, 218, 555, 2]

subfig.add_trace(go.Pie(labels=cols, values=count, showlegend=True), 1,1)
subfig.add_trace(go.Bar(x=cols, y=count, showlegend=False),1,2)

subfig.update_layout(
    template="plotly_dark", title='Patient Enrollment'
)
subfig.show()

感谢您的帮助。

go.Pie 需要 marker=dict(colors="...") 而 go.Bar 需要 marker_color="..."

由于您有 5 个不同的值,我们可以创建颜色列表

colors=['red','green','blue','yellow','purple']

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

subfig = make_subplots(
    rows=1, cols=2,
    column_widths=[10,10],
    row_heights=[10],
    subplot_titles=("Enrollment by Percentage", "Enrollment by Status"),
    specs=[[{"type": "pie"}, {"type": "bar"}]])

colors = ['red','green','blue','yellow','purple']  # bar and pie colors

cols = ['Baseline Failure', 'Exited Study', 'Screen Failure', 'Enrolled', 
        'Completed Study']

count = [146, 33, 218, 555, 2]

subfig.add_trace(go.Pie(labels=cols, values=count, marker=dict(colors=colors), 
                 showlegend=True), 1,1)

subfig.add_trace(go.Bar(x=cols, y=count,marker_color=colors, 
                 showlegend=False),1,2)

subfig.update_layout(template="plotly_dark",
                     title='Patient Enrollment')

subfig.show()