简体   繁体   English

在 altair plot 中为一些 x 标签着色?

[英]Color some x-labels in altair plot?

How can I change the color of only some x or y-labels?如何仅更改某些 x 或 y 标签的颜色?

For example, in the example below, I would like the y-ticks 4,5,6 and 7 to have red color, while the rest remain black.例如,在下面的示例中,我希望 y 刻度 4、5、6 和 7 具有红色,而 rest 保持黑色。 例子

Use alt.condition to get a conditional axis label color:使用alt.condition获取条件轴 label 颜色:

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'))
    ))
)

在此处输入图像描述

Change color of one tick one-by-one using plt.gca().get_yticklabels() object, and by using set_color attribute of this object change default color with conditon使用plt.gca().get_yticklabels() object 逐个更改一个刻度的颜色,并使用此 object 的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()

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

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