change the color of a specific scale on the y-axis in matplotlib

Asked 2 years ago, Updated 2 years ago, 67 views

I would like to change the color of a specific scale on the y-axis in matplotlib.
I'd like to change the color of values 2, 3, and 8 on the y-axis to blue.

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

plt.yticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
           ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"])

plt.show()

I don't know how to solve it. Thank you.

python matplotlib

2022-09-30 21:14

1 Answers

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

_,labels=plt.yticks(
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"])
labels[2].set_color("green")
labels[3].set_color("yellow")
labels[8].set_color("red")
plt.show()

yticks() (matplotlib.pyplot.yticks) returns an array of YTicks (which is not required here, so substitute _) and Text for you want to change color.Call http://matplotlib.org/api/pyplot_api.html?highlight=yticks#matplotlib.pyplot.yticks"rel="nofollow">matplotlib.text.Text.set_color to change it.

In the example provided, 0, 1, 2, ... and ticks were simple, but if not, you may want to call get_text() in Text (matplotlib.text.text.text.get_text) and change the color after checking the tick string.


2022-09-30 21:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.