如何使用matplotlib创建相同数量的主要和次要y轴刻度?

时间:2015-02-17 16:36:24

标签: python matplotlib plot

我已经工作了一段时间来创建一个带辅助轴的绘图,这样主轴和辅助轴的主刻度数就相等,这样网格线就会重合。在下图中,我在辅助轴上显示了网格线以说明问题。

enter image description here

通过手动设置辅助轴限制,我得到了这个图,这是我想要的输出:

enter image description here

我已经包含了可重现的代码:

import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('data.dat', skiprows=2, delimiter=',', unpack=True).transpose()
time = data[:,0]
pressure = data[:,1]
lift = data[:,2]
figure_pressure_trace = plt.figure(figsize=(5.15, 5.15))
figure_pressure_trace.clf()
P_vs_t = plt.subplot(111)
P_vs_t.plot(time, pressure, linewidth=1.0)
P_vs_t.set_ylabel(r'\textit{Pressure (bar)}', labelpad=6)
P_vs_t.set_xlabel(r'\textit{Time (ms)}', labelpad=6)
lift_vs_t = P_vs_t.twinx()
lift_vs_t.plot(time, lift, color='#4DAF4A')
lift_vs_t.set_ylabel(r'\textit{Lift(mm)}', labelpad=6)
plt.show()
plt.close()

数据可用here

更新

我创建了一个函数来创建相同数量的刻度,整个代码是:

import numpy as np
import matplotlib.pyplot as plt

def equal_y_ticks(primary, secondary):
    y_min_primary, y_max_primary = primary.get_ybound()
    y_min_secondary, y_max_secondary = secondary.get_ybound()
    primary_ticks = len(primary.yaxis.get_major_ticks())
    secondary_ticks = len(secondary.yaxis.get_major_ticks())
    primary_spacing = (y_max_primary - y_min_primary) / (primary_ticks - 1)
    secondary_spacing = (y_max_secondary - y_min_secondary) / (secondary_ticks - 1)
    ticks = max(primary_ticks, secondary_ticks)
    if secondary_ticks < primary_ticks:
        y_max_secondary = y_min_secondary + (primary_ticks * secondary_spacing)
        secondary.yaxis.set_ticks(np.arange(y_min_secondary, y_max_secondary, secondary_spacing))
    else:
        y_max_primary = y_min_primary + (secondary_ticks * primary_spacing)
        primary.yaxis.set_ticks(np.arange(y_min_primary, y_max_primary, primary_spacing))

data = np.loadtxt('data.dat', skiprows=2, delimiter=',', unpack=True).transpose()
time = data[:,0]
pressure = data[:,1]
lift = data[:,2]
figure_pressure_trace = plt.figure(figsize=(5.15, 5.15))
figure_pressure_trace.clf()
P_vs_t = plt.subplot(111)
P_vs_t.plot(time, pressure, linewidth=1.0)
P_vs_t.set_ylabel(r'\textit{Pressure (bar)}', labelpad=6)
P_vs_t.set_xlabel(r'\textit{Time (ms)}', labelpad=6)
lift_vs_t = P_vs_t.twinx()
lift_vs_t.plot(time, lift, color='#4DAF4A')
equal_y_ticks(P_vs_t, lift_vs_t)
lift_vs_t.set_ylabel(r'\textit{Lift(mm)}', labelpad=6)
plt.show()
plt.close()

但是这个函数给了我这样的图(对于一些数据):

enter image description here

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找LinearLocator (docs)

import matplotlib.pyplot as plt
from matplotlib import ticker as mtick
fig, ax = plt.subplots()
ax2 = ax.twinx()

ax.yaxis.set_major_locator(mtick.LinearLocator(5))
ax2.yaxis.set_major_locator(mtick.LinearLocator(5))

ax.set_ylim(0, 15)
ax2.set_ylim(0, 1500)
ax.yaxis.grid(True, lw=7, color='g', ls='--')
ax2.yaxis.grid(True, color='k', ls='-', lw=3)

将在最小值和最大值之间放置N个均匀间隔的刻度。

enter image description here