0

Assume if I wanted to change the tick label of '2' from Y axis to 'B' I used plt.yticsk(2,'B') but it seem to not work out

Is there any way to modify it? here's the code:

import matplotlib.pyplot as plt 

y = [-1,2,3,4,5,0,1]
x = [3,5,3,9,7,1,4]

colorsValue = []
for value in x:
    if value < 4:
        colorsValue.append('yellow')
    elif value >= 4:
        colorsValue.append('red')
    else:
        colorsValue.append('orange')

plt.barh(y, x, color = colorsValue)

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

plt.yticks(2,'b')

plt.show()
Henry Davis
  • 101
  • 1
  • 9

2 Answers2

2

you could find inspiration by checking how making what you expect here: https://www.python-graph-gallery.com/191-custom-axis-on-matplotlib-chart

The result might be as below:

import matplotlib.pyplot as plt

y = [-1,2,3,4,5,0,1]
x = [3,5,3,9,7,1,4]
yticks = ['-1','b','3','4','5','0','1']

colorsValue = []
for value in x:
    if value < 4:
        colorsValue.append('yellow')
    elif value >= 4:
        colorsValue.append('red')
    else:
        colorsValue.append('orange')

plt.barh(y, x, color = colorsValue)

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

plt.yticks(y,yticks)

plt.show()

Is that the result you expected?

enter image description here

Mr. T
  • 11,960
  • 10
  • 32
  • 54
ngenne
  • 86
  • 1
  • 3
1

you need to query the locations (so-called ticks) and labels first, then you can modify those and set those to your pyplot-object named plt:

import matplotlib.pyplot as plt 
import matplotlib.text

y = [-1,2,3,4,5,0,1]
x = [3,5,3,9,7,1,4]

colorsValue = []
for value in x:
    if value < 4:
        colorsValue.append('yellow')
    elif value >= 4:
        colorsValue.append('red')
    else:
        colorsValue.append('orange')

plt.barh(y, x, color = colorsValue)

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

ticks, labels = plt.yticks()
for i,t in enumerate(ticks):
    labels[i].set_text(t)
    if t == 2:
        labels[i].set_text('b')
plt.yticks(ticks,labels)

plt.show()

This is the resulting plot:

enter image description here

jgru
  • 181
  • 5
  • I thought, that it is only of relevance to change on label. The solution could be easily extended to preserve the other, pre-existing labels. I updated my answer, please check it , @Mr.T – jgru Jan 06 '22 at 16:23
  • Thanks for helping out with embedding the figure, @Mr.T! – jgru Jan 06 '22 at 16:34