在Python中仅绘制x-y图中的x轴次网格线

时间:2015-10-15 22:07:31

标签: python matplotlib grid

在下面的代码片段中,我得到了y轴和x轴的小网格线。如何仅绘制x轴次网格线?这是我的代码片段:

plt.subplot(212)
plt.ylim((-500,500))
plt.yticks(np.arange(-500,501,100))
plt.xlim((0,8))
plt.plot(time_ms, freq)
plt.plot(time_ms, y2, color='r', lw=1)
plt.plot(time_ms, y3, color='r', lw=1)
plt.fill_between(time_ms, y2, 500, color='red', alpha=0.3)
plt.fill_between(time_ms, y3, -500, color='red', alpha=0.3)
plt.grid(b=True, which='major', color='k', linestyle='-')
plt.grid(which='minor', color='k', linestyle=':', alpha=0.5)
plt.title("Response Plot")
plt.xlabel('Time (ms)')
plt.ylabel('Voltage (V)')
plt.minorticks_on()
plt.show()

1 个答案:

答案 0 :(得分:1)

使用matplotlib's面向对象的方法更容易。您可以对代码进行的最小更改是添加:

plt.gca().set_xticks(np.arange(0,8.2,0.2),minor=True)
设置xlim后的

行。 (显然,您可以更改arange作业中次要刻度的频率。在下图中,为简单起见,我注释掉了代码的y2和y3部分。

enter image description here

然而,更强大的解决方案是改变面向对象的方法。使用tickerMultipleLocator来选择次要的刻度位置(以及yticks)也可能是最安全的,因为如果你然后在图上平移,那么刻度是''硬连线,不会破坏。另请参阅this example

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as ticker

time_ms = np.arange(0,9,0.1)
freq = -500 + 1000.*np.random.rand(time_ms.shape[0])

majorYlocator = ticker.MultipleLocator(100)
majorXlocator = ticker.MultipleLocator(1)
minorXlocator = ticker.MultipleLocator(0.2)

ax = plt.subplot(212)

ax.set_ylim((-500,500))
ax.yaxis.set_major_locator(majorYlocator)
ax.set_xlim((0,8))
ax.xaxis.set_major_locator(majorXlocator)
ax.xaxis.set_minor_locator(minorXlocator)

ax.plot(time_ms, freq)
ax.plot(time_ms, y2, color='r', lw=1)
ax.plot(time_ms, y3, color='r', lw=1)
ax.fill_between(time_ms, y2, 500, color='red', alpha=0.3)
ax.fill_between(time_ms, y3, -500, color='red', alpha=0.3)

ax.grid(b=True, which='major', color='k', linestyle='-')
ax.grid(which='minor', color='k', linestyle=':', alpha=0.5)

ax.set_title("Response Plot")
ax.set_xlabel('Time (ms)')
ax.set_ylabel('Voltage (V)')

plt.show()