如何在matplotlib中的网格线之间制作轴?

时间:2018-05-15 13:05:08

标签: python matplotlib

在下面的简单示例中,如何使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

我希望结果如下: enter image description here

2 个答案:

答案 0 :(得分:1)

您可以设置次要刻度,以便在主要刻度之间只显示1个小刻度。这是使用matplotlib.ticker.AutoMinorLocator完成的。然后,将网格线设置为仅显示在次要刻度线上。您还需要将xtick位置移动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()

enter image description here

编辑:我无法让两个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

答案 1 :(得分:0)

如果你使用plt.subplots创建图形,你也会得到一个轴对象:

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

相关问题