简体   繁体   English

如何在 Altair 条形图中突出显示具有不同 colors 的 2 个条形图?

[英]How to highlight 2 bars with different colors in an Altair bar graph?

I would like to highlight two different bars in an Altair bar graph.我想在 Altair 条形图中突出显示两个不同的条形。 However, each one has to have a different color, based on a different condition.但是,根据不同的条件,每个人都必须具有不同的颜色。

The basics:基础知识:

import altair as alt
import pandas as pd

df = pd.DataFrame({"fruits": ["banana", "plum", "apple", "lime"], "values": [10, 6, 8, 5]})

plot = (
    alt.Chart(df)
    .mark_bar()
    .encode(
        x=alt.X("fruits", sort="y"),
        y="values"))

apple_plot = plot.encode(color=alt.condition(alt.datum.fruits == "apple", alt.value("red"), alt.value("navy")))

banana_plot = plot.encode(color=alt.condition(alt.datum.fruits == "banana", alt.value("yellow"), alt.value("navy")))

apple_plot | banana_plot

The result so far到目前为止的结果

条形图

What I tried我试过的

apple_banana_plot = plot.encode(
    color=alt.condition(
        alt.datum.fruits == "apple",
        alt.value("red"),
        alt.condition(
            alt.datum.fruits == "banana",
            alt.value("yellow"),
            alt.value("navy"))))

apple_banana_plot

The error I got:我得到的错误:

TypeError: type object got multiple values for keyword argument 'condition' TypeError:类型 object 获得了关键字参数“条件”的多个值

...which means I cannot use a condition inside another. ...这意味着我不能在另一个条件中使用条件。

The result I expect我期待的结果

预期的

You can do it like this: Basically, you define color with two parameters:你可以这样做:基本上,你用两个参数定义color

  • domain - the list of values in the categorical column domain - 分类列中的值列表
  • range - specific values of colors范围 - 具体值 colors
df = pd.DataFrame({"fruits": ["banana", "plum", "apple", "lime"], "values": [10, 6, 8, 5]})

plot = (
    alt.Chart(df)
    .mark_bar()
    .encode(
        x=alt.X("fruits", sort="y"),
        y="values",
    color=alt.Color('fruits',
                     scale=alt.Scale(
                         domain=df.sort_values(['values'])['fruits'].tolist(),
                         range=['navy', 'navy', 'red', 'yellow']))))
plot

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM