【问题标题】:How to share legend colors between two subplots in Plotly如何在 Plotly 中的两个子图之间共享图例颜色
【发布时间】:2021-06-20 04:08:24
【问题描述】:

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

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

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()

感谢您的帮助。

【问题讨论】:

    标签: python-3.x data-visualization plotly-python


    【解决方案1】:

    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()
    

    【讨论】:

      猜你喜欢
      • 2023-04-08
      • 1970-01-01
      • 2020-06-30
      • 2021-02-22
      • 2022-11-24
      • 1970-01-01
      • 2012-12-15
      • 2021-03-14
      • 1970-01-01
      相关资源
      最近更新 更多