2015-10-15 76 views
0

在下面的代码片段中,我得到了y轴和x轴次要网格线。我如何去绘制x轴次要网格线?这里是我的代码片段:在Python中绘制x-y图形中的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

这是更简单。使用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() 
相关问题