为 pyplot 轴刻度标签设置小数位

时间:2021-05-13 20:47:44

标签: python matplotlib axis-labels

我想使用 np.arange() 来定义轴刻度标签。但是有几个标签会出现疯狂的小数位(例如,0.850000000000000001 而不是 0.85)。使用 np.around() 到 2 个小数也无济于事,因为这些数字具有交替的小数位(0.45、0.5、0.55...)。我怎样才能让它把每个刻度标签写成两位小数?另外,我想为这些标签更改 fontsize,因此我需要调用 ax.set_yticklabels()

x,y = np.arange(0,1,.05), np.arange(0,1,.05)
fig, ax = plt.subplots(1,1)
ax.plot(x,y)
ax.set_yticks(np.arange(0,1,.05))
ax.set_yticklabels(np.arange(0,1,.05))

1 个答案:

答案 0 :(得分:0)

只需消除 ax.set_yticklabels()。没有它你会得到想要的结果。

x,y = np.arange(0,1,.05), np.arange(0,1,.05)
fig, ax = plt.subplots(1,1)
ax.plot(x,y)
ax.set_yticks(np.arange(0,1,.05))

enter image description here

您可以更改 yticklabels 的字体大小,如下所示:

plt.rc('ytick', labelsize=8)
x,y = np.arange(0,1,.05), np.arange(0,1,.05)
fig, ax = plt.subplots(1,1)
ax.plot(x,y)
ax.set_yticks(np.arange(0,1,.05))

enter image description here