2014-11-21 25 views
0

我想在Matplotlib(Python 2.7)中沿y軸設置主要和次要間隔的數量。我如何設置間隔數有些問題。他們並不總是與主要的網格線相匹配。在matplotlib中爲特定的主要/次要打勾頻率自動設置y軸刻度

這裏是我使用的設置刻度間隔和產生的情節代碼:

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
from matplotlib.ticker import MultipleLocator 

# --------------USER INPUT SECTION---------------------- 
# Generating x and y values: 
ind_ex = np.arange(16) 
df2a = pd.DataFrame(np.random.randn(len(ind_ex), 5), columns = list('ABCDE'), index=ind_ex) 
x_var = np.arange(len(ind_ex)) 
x_var_plot = 'X variable' 
df2a.insert(0, x_var_plot, x_var) 
x_values = df2a[x_var_plot] #this is the x-variable (a list passed into a dataframe column) 
y_values = df2a[df2a.columns.values.tolist()[1:]] #columns 2 onwards are the y-variables (the list part, or the values, of a dataframe column) 
label_entries = df2a.columns.tolist()[1:] #label names are column names for column 2 onwards 

# Setting line thickness, length and width: 
thck_lines = 1 
len_maj_ticks = 10 #length of major tickmarks 
len_min_ticks = 5 #length of minor tickmarks 
wdth_maj_tick = 1 #width of major tickmarks 
wdth_min_tick = 1 #width of minor tickmarks 

# Setting y-axis major and minor intervals: 
y_axis_intervals = 10 #number of major intervals along y-axis 
y_minor_intervals = 5 #number of minor intervals along y-axis 
# ------------------------------------------------------ 

# Matplotlib (Plotting) section follows: 
fig = plt.figure(1) 
ax = fig.add_subplot(111) 
ax.plot(x_values, y_values, alpha=1, label = label_entries, linewidth = thck_lines) 

# Set the y-axis limits, for tickmarks, and the major tick intervals: 
starty, endy = ax.get_ylim() 
ax.yaxis.set_ticks(np.arange(starty, endy+1, (endy-starty)/y_axis_intervals)) 

# Set the y-axis minor tick intervals: 
minorLocatory = MultipleLocator((endy-starty)/y_axis_intervals/y_minor_intervals) #y-axis minor tick intervals 
ax.yaxis.set_minor_locator(minorLocatory) #for the minor ticks, use no labels; default NullFormatter (comment out for log-scaled y-axis) 

ax.grid(True) 
ax.tick_params(which='minor', length=len_min_ticks, width = wdth_min_tick) #length and width of both x and y-axis minor tickmarks 
ax.tick_params(direction='out') 
ax.tick_params(which='major', width=wdth_maj_tick) #width of major tickmarks 
ax.tick_params(length=len_maj_ticks) #length of all tickmarks 

plt.show() 

我剛纔所用的例子here的設置間隔。問題在於,就我而言,y軸主要網格線並不總是與主要滴答間隔排列在一起 - 請參閱圖片。如果我運行此代碼4或5次,則會出現此問題。

如何正確設置y軸間隔,使主要y軸網格線與刻度線正確對齊?

enter image description here

回答

0

我將要發佈此作爲我試圖回答我的問題:後

from matplotlib.ticker import MultipleLocator, AutoMinorLocator 

,並加入這一行(41行):

我換4號線第40行:

ax.yaxis.set_minor_locator(AutoMinorLocator(y_minor_intervals)) 

。如果我刪除第40行,則得到與保留第40行相同的結果,因此我不確定是否需要第40行和第41行(此處爲第2行代碼),或者第41行是否正確擁有。所以,我真的不知道我的兩個改變是否是最好的辦法,或者他們只是在工作,因爲我在某個地方犯了兩個錯誤。

如果有人可以確認這一點,那麼這將非常有幫助。