在 Python 上的 Plotly 中手动定义图例

Posted

技术标签:

【中文标题】在 Python 上的 Plotly 中手动定义图例【英文标题】:Manually defined legend in Plotly on Python 【发布时间】:2021-12-09 12:22:33 【问题描述】:

我有一些按天细分的数据。对于每一天,我在一天的开始和结束时都有一个数据点,每个数据点的值都在 0 到 100 之间。我需要将此数据显示为分组条形图,其中 x 轴上的日期,y 轴上的值条形颜色由它们的值决定。对于每一天,左边栏需要有相应的开始值,右边栏显示当天的结束值。然而,图例需要显示颜色信息而不是迹线 情节基本上需要看起来像这样,但图例需要显示“绿色”、“琥珀色”、“红色”而不是“开始”、“结束”。

I need the plot to look like this but with a legend describing the colors rather than the traces

这里是一些重现情节的代码:

x = ["day"+str(i) for i in range(1,8)]
starts = [10, 50, 70, 75, 20, 50, 90]
ends = [95, 5, 80, 20, 50, 10, 75]
starts_colors = ['green', 'orange', 'red', 'red', 'green', 'orange', 'red']
ends_colors = ['red', 'green', 'red', 'green', 'orange', 'green', 'red']

这是我上面的情节的代码。

layout = go.Layout(showlegend=True) 
fig = go.Figure(layout=layout)
fig.add_trace(go.Bar(x=x, y=starts, name = 'start', marker=dict(color=starts_colors)))
fig.add_trace(go.Bar(x=x, y=ends, name = 'end', marker=dict(color=ends_colors)))
fig.show()

如果我将数据重新排列成 3 条轨迹(每种颜色一条),并在开始和结束时使用相应的值,我最终会在条形之间出现间隙。例如,“day1”会在中间有一个间隙,因为“day1”没有橙色条。

这似乎是一个简单的问题,但我不知道如何让它按照我应该的方式工作。

【问题讨论】:

【参考方案1】: 这将准确地创建您请求的图表 首先将您的示例数据放入数据框中以打开 Plotly Express 首先更新跟踪以使用颜色列 添加图例完成。真的不是功能图例,因为它不能用于过滤图形,只会显示图形中使用的独特颜色。这是通过添加额外的 small 跟踪来实现的
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import numpy as np

df = pd.DataFrame(
    
        "day": ["day" + str(i) for i in range(1, 8)],
        "starts": [10, 50, 70, 75, 20, 50, 90],
        "ends": [95, 5, 80, 20, 50, 10, 75],
        "starts_colors": ["green", "orange", "red", "red", "green", "orange", "red"],
        "ends_colors": ["red", "green", "red", "green", "orange", "green", "red"],
    
)

# build figure, hover_data / customdata is used to hold colors
fig = px.bar(
    df,
    x="day",
    y=["starts", "ends"],
    barmode="group",
    hover_data="starts_colors":False, "ends_colors":False,
)

# update colors of bars
fig.plotly_update(
    data=[
        t.update(marker_color=[c[i] for c in t.customdata])
        for i, t in enumerate(fig.data)
    ]
)

# just for display purpose, create traces so that legend contains colors.  does not connect with
# bars
fig.update_traces(showlegend=False).add_traces(
    [
        go.Bar(name=c, x=[fig.data[0].x[0]], marker_color=c, showlegend=True)
        for c in np.unique(df.loc[:,["starts_colors","ends_colors"]].values.ravel())
    ]
)

【讨论】:

像魅力一样工作。谢谢!

以上是关于在 Python 上的 Plotly 中手动定义图例的主要内容,如果未能解决你的问题,请参考以下文章

在条形图上的 Plotly 中更改轴/图例名称

如何使用 plotly 自定义平行类别图颜色? Python版

Plotly:使用 Python 在多线图中添加色阶

plotly Sankey 图:如何更改节点的默认顺序

Plotly:如何在甘特图上标记条形?

在 jupyter notebook 中使用 plotly python 绘制具有不等热图的交互式树状图