简体   繁体   中英

Automatically set y-axis ticks in matplotlib for particular major/minor tick frequency

I am trying to set the number of major and minor intervals along the y-axis in Matplotlib (Python 2.7). Something is wrong with how I am setting the number of intervals. They are not always lining up with the major gridlines.

Here is the code that I am using to set the tick intervals and generate the plot:

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()

I have made use of the example here to set the intervals. The problem is that, in my case, the y-axis major gridlines are not always lining up with the major tick intervals - see the picture. If I run this code 4 or 5 times, this problem occurs.

How can I set the y-axis intervals correctly so that the major y-axis gridlines are correctly lined up with the tick marks?

在此处输入图片说明

I will have to post this as my attempt to answer my own question:

I changed line 4 to:

from matplotlib.ticker import MultipleLocator, AutoMinorLocator

and added this line (line 41) after line 40:

ax.yaxis.set_minor_locator(AutoMinorLocator(y_minor_intervals))

respectively. If I remove line 40, then I get the same result as if I keep line 40, so I am not sure if I need both line 40 and the new line 41 (2nd line of code here) or if line 41 is correct on its own. So, I really don't know if my 2 changes are the best way to do this, or if they are just working because I am making 2 mistakes somewhere.

If someone could please confirm this, then that would be really helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM