如何获取对当前图形和轴对象的引用,以便我可以强制条形图 y 轴仅显示整数

imr*_*nal 2 matplotlib python-3.x

有人提出了类似的问题:

如何强制 matplotlib 在 Y 轴上仅显示整数

我正在尝试对条形图执行完全相同的操作。我的问题是 bar 对象没有解压到Fig、ax。这是代码:

import matplotlib.pylab as plt
x = [0, 0.5, 1, 2, 3, 3.5, 4, 4.5, 5, 7.5, 8.5,9]
y = [1,2,2,3,1,2,2,2,2,1,1,0]
width = 0.5
plt.bar(x, y, width, color="pink")
plt.xlabel('score')
plt.ylabel('antall')
plt.show()
Run Code Online (Sandbox Code Playgroud)

和条形图:

条形图

我只想在 y 轴上显示整个整数,在 x 轴上显示相反的整数(即数字 0 到 10,增量为 0.5)。

tmd*_*son 6

您可以使用fig = plt.gcf()ax = plt.gca()来获取对当前图形和轴对象的引用。

但是,使用matplotlib 面向对象的界面始终可以让您访问figax并使代码更清晰您正在控制的图形和轴。

Also, you can use the matplotlib.ticker module for more control over tick locations. In this case, a MultipleLocator will do the trick to set the tick locations on multiples of 1 for the yaxis and 0.5 for the xaxis.

import matplotlib.pylab as plt
import matplotlib.ticker as ticker

x = [0, 0.5, 1, 2, 3, 3.5, 4, 4.5, 5, 7.5, 8.5,9]
y = [1,2,2,3,1,2,2,2,2,1,1,0]

fig, ax = plt.subplots(1)

width = 0.5
ax.bar(x, y, width, color="pink")
ax.set_xlabel('score')
ax.set_ylabel('antall')

ax.xaxis.set_major_locator(ticker.MultipleLocator(0.5))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述