自动设置特定主要/次要刻度频率的 y 轴刻度

问题描述 投票:0回答:1

我试图在 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 轴网格线与刻度线正确对齐?

enter image description here

python python-2.7 matplotlib plot axis-labels
1个回答
0
投票

我必须将其发布为我试图回答我自己的问题:

我将第 4 行更改为:

from matplotlib.ticker import MultipleLocator, AutoMinorLocator

并在第 40 行之后添加了这一行(第 41 行):

ax.yaxis.set_minor_locator(AutoMinorLocator(y_minor_intervals))

分别。如果我删除第 40 行,那么我会得到与保留第 40 行相同的结果,所以我不确定是否需要第 40 行和新的第 41 行(此处是代码的第二行),或者第 41 行在其上是否正确自己的。所以,我真的不知道我的两个改变是否是最好的方法,或者它们是否只是有效,因为我在某个地方犯了两个错误。

如果有人可以确认这一点,那将非常有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.