【发布时间】:2014-11-21 16:02:37
【问题描述】:
我正在尝试在 Matplotlib (Python 2.7) 中设置沿 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 轴网格线与刻度线正确对齐?
【问题讨论】:
标签: python python-2.7 matplotlib plot axis-labels