【问题标题】:how to use seaborn objects scale with two visualisations with same kwargs?如何使用具有相同 kwargs 的两个可视化的 seaborn objects scale?
【发布时间】:2023-01-20 09:04:29
【问题描述】:

我正在尝试在条形图上创建带有标签的条形图。标签的位置和标签的颜色取决于数据框的列。另外,我想按列给条形图上色。

我的数据:

data = {
    'Survived': ['0', '1'],
    'count': [500, 100],
    'label_position': ['R', 'L']
}
df = pd.DataFrame(data)

我试图创建以下情节:

import seaborn.objects as so

p = (
    so.Plot(df, x='count', y='Survived')
    .add(so.Bar(alpha=1), color='Survived')
    .add(
            so.Text({"fontweight": "bold"}),
            text='count',
            halign='label_position',
            color="label_position"
        )
    .scale(
        halign={'L':'left', 'R':'right'},
        color={'L':'black', 'R':'white'}
        )
    )
p.plot()

但是此代码引发以下错误:

PlotSpecError: Scale setup failed for the `color` variable. See the traceback above for more information.

因为两个可视化都有属性颜色。

我可以同时使用颜色条或文本,但不能同时使用。

彩条: color the bars

彩色文字: color the text

有没有可能把两者都涂上颜色?

【问题讨论】:

    标签: seaborn seaborn-0.12.x


    【解决方案1】:

    如果我们 see the traceback above for more information 如异常消息所示,它说

    ValueError: No entry in color dictionary for '0', '1'
    

    所以我们可以尝试为这些键添加条目:

    (
        so.Plot(df, x='count', y='Survived')
        .add(so.Bar(alpha=1), color='Survived')
        .add(
            so.Text({"fontweight": "bold"}),
            text='count',
            halign='label_position',
            color="label_position",
        )
        .scale(
            halign={'L':'left', 'R':'right'},
            color={'L':'black', 'R':'white', '0': 'black', '1': 'white'},  # <-----
        )
    )
    

    这行得通,但现在我们在图例中有一些我们可能不想要的条目。通常没有一种方法可以独立于Nominal 比例实际映射的内容来控制图例中显示的内容,但是对于这个特定的图,颜色编码无论如何都是多余的,因此我们实际上不需要图例:

    (
        so.Plot(df, x='count', y='Survived')
        .add(so.Bar(alpha=1), color='Survived', legend=False)  # <-----
        .add(
            so.Text({"fontweight": "bold"}),
            text='count',
            halign='label_position',
            color="label_position",
        )
        .scale(
            halign={'L':'left', 'R':'right'},
            color={'L':'black', 'R':'white', '0': 'black', '1': 'white'},
        )
    )
    

    【讨论】:

      猜你喜欢
      • 2013-05-25
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 2016-05-07
      • 2017-12-17
      • 2018-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多