如何在matplotlib中使坐标轴刻度线位于网格线之间?

5
在下面的简单示例中,如何使x轴刻度值出现在网格之间?
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(1)
x = range(10)
y = np.random.random(10)
plt.plot(x,y)
plt.xticks(x)
plt.grid(True)
plt.show()

enter image description here

以下代码可以让刻度线出现在我想要的位置,但是网格线也会移动。
np.random.seed(1)
x = range(10)
y = np.random.random(10)
plt.plot(x,y)
plt.xticks(x)
plt.grid(True)
plt.xticks(np.arange(10)+0.5, x)
plt.show()

enter image description here

我希望结果是:

我想要的结果是: 在此输入图片描述


当您使用随机函数时,需要设置种子,以便输出结果是“随机”的,但具有一致的结果。请参阅np.random.seed() - IMCoins
2个回答

5

您可以设置次刻度,使得在两个主刻度之间只有1个次刻度。这可以通过使用matplotlib.ticker.AutoMinorLocator来完成。然后,将网格线设置为仅出现在次刻度处。您还需要将x轴刻度位置向右移动0.5:

from matplotlib.ticker import AutoMinorLocator

np.random.seed(10)

x = range(10)
y = np.random.random(10)
plt.plot(x,y)
plt.xticks(np.arange(0.5,10.5,1), x)
plt.xlim(0,9.5)
plt.ylim(0,1)
minor_locator = AutoMinorLocator(2)
plt.gca().xaxis.set_minor_locator(minor_locator)
plt.grid(which='minor')

plt.show()

在这里输入图片描述

编辑:我在同一轴上使用两个 AutoMinorLocator 时遇到了问题。当试图为 y 轴添加另一个轴时,次刻度线会出现混乱。我发现的一种解决办法是手动设置次刻度线的位置,使用 matplotlib.ticker.FixedLocator 并传入次刻度线的位置。

from matplotlib.ticker import AutoMinorLocator
from matplotlib.ticker import FixedLocator
np.random.seed(10)

x = range(10)
y = np.random.random(10)
plt.plot(x,y)
plt.xticks(np.arange(0.5,10.5,1), x)
plt.yticks([0.05,0.15,0.25,0.35,0.45,0.55,0.65,0.75,0.85,0.95,1.05], [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1])
plt.xlim(0,9.5)
plt.ylim(0,1.05)

minor_locator1 = AutoMinorLocator(2)
minor_locator2 = FixedLocator([0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1])
plt.gca().xaxis.set_minor_locator(minor_locator1)
plt.gca().yaxis.set_minor_locator(minor_locator2)
plt.grid(which='minor')

plt.show()

enter image description here


谢谢,但是这种方法似乎移动了网格。有没有办法移动标签而不是网格? - A.Razavi
你能提供一个示例图像,说明你想要哪些刻度线和网格线的位置吗?因为对我来说不是100%清楚。 - DavidG
抱歉,我在上面的问题末尾添加了所需的结果图片。 - A.Razavi
@DavidG,谢谢。这已经帮了很多忙了。有没有办法对y轴做同样的事情?让网格在0.0、0.1、0.2等处,但标签为0.1、0.2等在网格之间? - A.Razavi

0
如果您使用plt.subplots创建图形,您也会得到一个axes对象:
f, ax = plt.subplots(1)

这个界面更好,可以调整网格/刻度。然后,您可以明确地为数据提供向左偏移0.5的x值。对于次要刻度也是如此,并让网格显示在次要刻度处:

f, ax = plt.subplots(1)
ax.set_xticks(range(10))
x_values = np.arange(10) - .5
ax.plot(x_values, np.random.random(10))
ax.set_xticks(x_values, minor=True)
ax.grid(which='minor')

enter image description here


我希望数值0、1、2等出现在网格线之间 - A.Razavi
谢谢,但这个方法也会移动网格而不是标签!如果您知道如何移动标签,请告诉我。 - A.Razavi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接