gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:56:27 24 4
gpt4 key购买 nike

我想在左右 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() 只在右轴上工作?

最佳答案

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

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

关于Matplotlib,如何在一侧内部和另一侧外部获得刻度线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56809407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com