matplotlib 为特定的主/次刻度频率自动设置Y轴刻度

bvjveswy  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(108)

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

5cg8jx4n

5cg8jx4n1#

我将不得不把这篇文章作为我回答自己问题的尝试:
我把第四行改成:

from matplotlib.ticker import MultipleLocator, AutoMinorLocator

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

ax.yaxis.set_minor_locator(AutoMinorLocator(y_minor_intervals))

如果我删除第40行,那么我得到的结果就和保留第40行一样,所以我不确定我是否需要第40行和新的第41行(这里的第二行代码),或者第41行本身是正确的。所以,我真的不知道我的两个更改是否是最好的方法,或者它们是否只是工作,因为我在某个地方犯了两个错误。
如果有人能证实这一点,那将是非常有帮助的。

相关问题