颜色离散贴图扰乱了情节时间轴中块的对齐

问题描述 投票:0回答:1

我有一个包含三个区块的情节时间表。当我不给它们上色时,它们就很好地对齐了。

import pandas as pd
df = pd.DataFrame.from_dict(
    {
        'y': [2,3,4],
        'van': [pd.Timestamp("2023-08-07 09:00"), pd.Timestamp("2023-08-07 14:30"), pd.Timestamp("2023-08-07 17:00")],
        'tot': [pd.Timestamp("2023-08-07 17:00"), pd.Timestamp("2023-08-07 22:30"), pd.Timestamp("2023-08-08 01:00")],
        'selected': [False, True, False]
    }
)

fig = px.timeline(df, x_start='van', x_end='tot', y='y',
                           color= "selected",
                           color_discrete_map = {True: "#CDCDD3", False: "#8C8C8F"},
                           )
fig.show()

这会产生以下漂亮的情节:

但是,现在我尝试使用 color_discrete_map 为它们着色,如下所示:

fig = px.timeline(df, x_start='van', x_end='tot', y='y',
                           color= "selected",
                           color_discrete_map = {True: "#CDCDD3", False: "#8C8C8F"},
                           )
fig.show()

然后剧情就奇怪地混乱了:

谁知道如何解决这个问题?

express colors plotly timeline
1个回答
0
投票

当您使用

color= "selected"
参数并且有不止一种可能的颜色时,似乎会发生这种情况 - 据我所知,这是一个错误(如果我有时间,我会提交错误报告)。

为了解决这个问题,您可以在不使用 color 参数的情况下创建无花果,这会将

fig.data
设置为一个
go.Bar
对象的元组,其中所有条形都具有相同的默认绘图颜色。然后我们可以使用所需的颜色映射手动将标记颜色分配给 go.Bar 对象。

import pandas as pd
import plotly.express as px

df = pd.DataFrame.from_dict(
    {
        'y': [2,3,4],
        'van': [pd.Timestamp("2023-08-07 09:00"), pd.Timestamp("2023-08-07 14:30"), pd.Timestamp("2023-08-07 17:00")],
        'tot': [pd.Timestamp("2023-08-07 17:00"), pd.Timestamp("2023-08-07 22:30"), pd.Timestamp("2023-08-08 01:00")],
        'selected': [False, True, False]
    }
)

fig = px.timeline(df, x_start='van', x_end='tot', y='y',)

## the fig is one go.Bar object
color_discrete_map = {True: "#CDCDD3", False: "#8C8C8F"}
colors = [color_discrete_map[s] for s in df['selected']]
fig.data[0]['marker'] = {'color': colors}
                           
fig.show()

© www.soinside.com 2019 - 2024. All rights reserved.