2015-10-15 150 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() 
相關問題