Change the colors of matplotlib's ticklabels based on a condition

Daniel Lima :

How can I change the colors of yticklabels based on a given condition?

I am looking for something similar to this chart (made in excel), where negative values are in red and positive in black.

enter image description here

Example code:

import matplotlib.pyplot as plt
import numpy as np

plt.plot(np.random.random(35)-0.5)
Liris :

You can use this example, and change the condition depending on what you want to do:

import matplotlib.pyplot as plt
import numpy as np

plt.figure()
ax = plt.gca()

plt.plot(np.random.random(35)-0.5)
labels = ax.get_yticklabels()
ticks = ax.get_yticks()
for label, tick in zip(labels, ticks):
  if tick < 0:
    label.set_color('r')

plt.show()

enter image description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=27803&siteId=1