简体   繁体   English

如何在 matplotlib 中为副轴设置 xtick position?

[英]How to set the xtick position for secondary axis in matplotlib?

I want to create a secondary xaxis at the top which has an inverse relation with the major xaxis at the bottom.我想在顶部创建一个辅助 xaxis,它与底部的主要 xaxis 成反比关系。 I followed the official tutorial here and have the following codes:我在这里按照官方教程进行操作并具有以下代码:

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

The problem is that the xticks at the top are not at the right place.问题是顶部的 xticks 不在正确的位置。 They are bunched together in the left due to the inverse function applied.由于应用了逆 function,它们在左侧聚集在一起。 How do I manually set the position of the xticks?如何手动设置 xticks 的 position? (eg at 10,20,40,70) (例如在 10、20、40、70)

Edit: Just to make it more clear, the ticks are at the right place, but there are too many tickss as shown in the figure.编辑:只是为了更清楚,滴答声在正确的位置,但是如图所示,滴答声太多了。 In this case, I only want the ticks at 10, 20, 40, 70 (I don't want the ticks at 30, 50 and 60 as we can't see all the tick numbers clearly)在这种情况下,我只想要 10、20、40、70 的刻度(我不想要 30、50 和 60 的刻度,因为我们无法清楚地看到所有刻度数) 在此处输入图像描述

I believe either you missed import statement for numpy or you need to update you matplotlib. Below works fine for me -我相信您要么错过了 numpy 的导入声明,要么您需要更新 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()

Check your version -检查你的版本 -

import matplotlib
print (matplotlib.__version__)

If above doesn't print 3.2.1.如果上面没有打印 3.2.1。 try below -试试下面 -

 pip install matplotlib==3.2.1

在此处输入图像描述

It is not clear what you want to achieve.目前尚不清楚你想要实现什么。

If you want a linear relationship at the top, this might be relevant:如果你想要顶部的线性关系,这可能是相关的:

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

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM