如何在matplotlib中设置辅助轴的xtick位置?

问题描述 投票:0回答:2

我想在顶部创建一个辅助xaxis,它与底部的主要xaxis成反比。我遵循了官方教程here,并具有以下代码:

def forward(x):
    return 10/x

def backward(y):
    return 10/y

fig, ax = plt.subplots()
ax.set_xlim([0.14, 1.4])
secax = ax.secondary_xaxis('top', functions=(forward, backward))
secax.set_xticks(np.array([10,20,40,70]))  # does not work!
plt.show()

问题是,顶部的xticks不在正确的位置。由于应用了逆函数,它们在左侧聚在一起。如何手动设置xticks的位置? (例如10,20,40,70)

编辑:为了更清楚一点,刻度线位于正确的位置,但是如图所示,刻度线太多。在这种情况下,我只希望刻度线在10、20、40、70(我不希望刻度线在30、50和60,因为我们无法清楚地看到所有刻度线号)enter image description here

python numpy matplotlib plot figure
2个回答
1
投票

我相信您可能错过了numpy的import语句,或者需要更新matplotlib。下面对我来说很好-

import matplotlib.pyplot as plt
import numpy as np

def forward(x):
    return 10/x

def backward(y):
    return 10/y

fig, ax = plt.subplots()
ax.set_xlim([0.14, 1.4])
secax = ax.secondary_xaxis('top', functions=(forward, backward))
secax.set_xticks(np.array([10,20,40,70]))  # does not work!
plt.show()

检查您的版本-

import matplotlib
print (matplotlib.__version__)

如果以上不打印3.2.1,尝试以下-

 pip install matplotlib==3.2.1

enter image description here


0
投票

不清楚要实现什么。

如果您想在顶部建立线性关系,则可能与之相关:

import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ax.set_xlim([0.14, 1.4])
secax = ax.secondary_xaxis('top', functions=(lambda x: 77 - 50 * x,
                                             lambda y: (77 - y) / 50))
secax.set_xticks(np.array([10, 20, 40, 70]))
plt.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.