Matplotlib,如何在一侧内部获得刻度线,在另一侧获得外部刻度线?

时间:2019-06-28 15:16:40

标签: 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()仅在右轴上工作?

2 个答案:

答案 0 :(得分:1)

刻度实际上在轴的两侧是相同的,因此不能仅在轴的一侧更改它们。

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

两种情况下的输出相同:

enter image description here

答案 1 :(得分:0)

我认为您需要定义一个双轴才能实现此目的。具体来说,您可以

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

enter image description here