在 altair 图中给一些 x 标签上色?

Color some x-labels in altair plot?

如何只更改某些 x 或 y 标签的颜色?

例如,在下面的示例中,我希望 y 刻度 4、5、6 和 7 为红色,而其余部分保持黑色。

使用 plt.gca().get_yticklabels() 对象逐个更改一个刻度的颜色,并使用此对象的 set_color 属性使用条件

更改默认颜色
from matplotlib import pyplot as plt
import pandas as pd

df = pd.DataFrame(
    {
        'x':['A', 'B', 'C', 'D', 'E'],
        'y':[5, 3, 6, 7, 2]
    }
)

plt.bar(df['x'], df['y'])

my_colors = 'red'

for ticklabel, y in zip(plt.gca().get_yticklabels(), range(max(df['y']))):
    if y in [4, 5, 2, 1]:
        ticklabel.set_color(my_colors)

plt.xlabel('X')
plt.ylabel('Y')
plt.show()

使用alt.condition获取条件轴标签颜色:

import altair as alt
import pandas as pd

df = pd.DataFrame({
    'x': ['A', 'B', 'C', 'D', 'E'],
    'y': [5, 3, 6, 7, 2],
})

alt.Chart(df).mark_bar().encode(
    x='x',
    y=alt.Y('y', axis=alt.Axis(
        labelColor=alt.condition('datum.value > 3 && datum.value < 7', alt.value('red'), alt.value('black'))
    ))
)