Andriy Drozdyuk
Andriy Drozdyuk

Reputation: 61021

Color some x-labels in altair plot?

How can I change the color of only some x or y-labels?

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. example

Upvotes: 5

Views: 1293

Answers (2)

jakevdp
jakevdp

Reputation: 86310

Use alt.condition to get a conditional axis label color:

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

enter image description here

Upvotes: 12

Davinder Singh
Davinder Singh

Reputation: 2162

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

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

Upvotes: 0

Related Questions