Matplotlib,如何在一边的内侧和另一边的外侧获得记号?

Matplotlib,如何在一边的内侧和另一边的外侧获得记号?,matplotlib,Matplotlib,我想在左右y轴上都有相应的记号。但是,我希望左y轴记号位于轴外部,右y轴记号位于轴内部 我所拥有的: import matplotlib.pyplot as plt ax = plt.subplot(1,1,1) ax.tick_params(axis='y',which='both',direction='in',right=True) 有没有办法让ax.tick_params()仅在右轴上工作?我认为需要定义一个双轴才能实现这一点。具体来说,你可以这样做 import matplotlib

我想在左右y轴上都有相应的记号。但是,我希望左y轴记号位于轴外部,右y轴记号位于轴内部

我所拥有的:

import matplotlib.pyplot as plt
ax = plt.subplot(1,1,1)
ax.tick_params(axis='y',which='both',direction='in',right=True)

有没有办法让ax.tick_params()仅在右轴上工作?

我认为需要定义一个双轴才能实现这一点。具体来说,你可以这样做

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.tick_params(axis='y', direction='out')

ax1 = ax.twinx()
ax1.tick_params(axis='y',direction='in')

实际上,轴两侧的记号是相同的,因此不能仅在轴的一侧更改记号

matplotlib<3.1的解决方案: 除了@Sheldore的答案外,人们可能还想共享双轴,否则双方都会失去同步

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.tick_params(axis="y", direction='in', length=8)

ax2 = ax.twinx()
ax2.tick_params(direction="out", right=True, length=8)
ax2.get_shared_y_axes().join(ax,ax2)

plt.show()
matplotlib>=3.1的解决方案 Matplotlib 3.1引入了次轴。这在以前需要误用双轴的许多情况下非常有用,如上所述。优点是,无需进一步的参数,它将自动同步

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.tick_params(axis="y", direction='in', length=8)

ax2 = ax.secondary_yaxis("right")
ax2.tick_params(axis="y", direction="out", length=8)

plt.show()
两种情况下的输出相同:


请注意,至少对于matplotlib<3.1答案,您需要在绘制任何数据之前执行此操作。