How to add yticks to one specific point

1k Views Asked by At

I have bunch of numbers (lets say all less than 500) and some 'inf' in my data. I want to plot them using integer numbers (I represent 'inf' with 1000). However, on y axis of plot, I want to write 'inf' instead of 1000. If I use 'plt.yticks', I can add label to all y points which is not what I want. How can I add a label to one specific point?

2

There are 2 best solutions below

0
On BEST ANSWER

You can override the both the data position of the ticks and the labels of the ticks. Here is an example of a scatter plot with 3 extra points at "infinity". It does not look great because the extra points are at 1000, and there are ticks showing in the white space.

from matplotlib import pyplot as plt
import numpy as np

# create some data, plot it.
x = np.random.random(size=300)
y = np.random.randint(0,500, 300)
x_inf = [0,.1,.2]
y_inf = [1000,1000,1000]

plt.scatter(x,y)
plt.scatter(x_inf, y_inf)

enter image description here

First grab the axis. Then we can overwrite what data positions should have ticks, in this case 0 to 500 in steps of 100, and then 1000. Then we can also overwrite the labels of the ticks themselves.

ax = plt.gca()
# set the positions where we want ticks to appear
ax.yaxis.set_ticks([0,100,200,300,400,500,1000])
# set what will actually be displayed at each tick.
ax.yaxis.set_ticklabels([0,100,200,300,400,500,'inf'])

enter image description here

1
On

Check this out:

plt.plot(np.arange(5), np.arange(5))
plt.yticks(np.arange(5), [200, 400, 600, 800, 'inf'])
plt.show()

enter image description here