如何将yticks添加到pyplot中的特定点?

时间:2018-12-07 02:31:15

标签: python matplotlib plot

我有一堆数字(假设所有数字都小于500)和数据中的一些“ inf”。我想使用整数绘制它们(我用1000表示'inf')。但是,在图的y轴上,我想写'inf'而不是1000。如果我使用'plt.yticks',我可以在所有y点上添加标签,这不是我想要的。如何在一个特定点添加标签?

2 个答案:

答案 0 :(得分:1)

您可以覆盖刻度线的数据位置和刻度线的标签。这是一个散点图的示例,在“无穷大”处有3个额外的点。看起来不太好,因为加分点为1000,并且在空白处显示刻度线。

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

首先抓住轴。然后,我们可以覆盖哪些数据位置应带有刻度线,在这种情况下,应以100为步长,然后是1000,再覆盖0至500。然后,也可以覆盖刻度线本身的标签。

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 :(得分:0)

检查一下:

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

enter image description here