微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

绘制上对数轴作为下线性轴的函数 次轴回调

如何解决绘制上对数轴作为下线性轴的函数 次轴回调

我想绘制一个带有线性 x 轴和 y 轴的图,加上一个对数顶部 x 轴,显示作为底部 x 轴函数的刻度。我不确定要传递给刻度的内容,或者单独定义函数来构建上对数轴刻度是否更方便(类似于here)。我希望以 0.1 为步长在上对数轴上显示刻度。 这是一个 MWE:

from matplotlib.ticker import ScalarFormatter,FormatStrFormatter

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np

fig,ax1 = plt.subplots(1,figsize=(10,6))

ax1.set_ylabel(r'y axis')
ax1.set_xlabel(r'Linear axis')
ax1.set_ylim(0.1,1.)
ax1.set_xlim(0.1,1.5)

#Upper lox-axis
new_tick_locations = 
[np.log(i*1.e37/(2.*(3.809e8))) for i in np.arange(0.1,10.,0.1)] #I should pass something else instead of arange
                                                  #I'd like the upper axis ticks in steps of 0.1 anyway

axup=ax1.twiny()
axup.set_xticks(new_tick_locations)

axup.set_xlabel(r'Log axis')
plt.show()

解决方法

次轴

更新:事实证明,使用 secondary_xaxis() 而不是 twiny() 更简单。您可以使用 functions 参数指定底部和顶部轴之间的变换和反函数:

import matplotlib.pyplot as plt
import numpy as np

fig,ax1 = plt.subplots(1,figsize=(10,6))

ax1.set_ylabel('y axis')
ax1.set_xlabel('Linear axis')
ax1.set_ylim(0.1,1.)
ax1.set_xlim(0.1e-9,1.5e-9)

# secondary x-axis transformed with x*(a*b) and inverted with x/(a*b)
a,b = 4.*np.pi,np.float64((2.*3.086e22)**2.) 
axup = ax1.secondary_xaxis('top',functions=(lambda x: x*(a*b),lambda x: x/(a*b)))
axup.set_xscale('log')
axup.set_xlabel('Log axis')

plt.show()

secondary log axis with new params

原始示例:

# secondary x-axis transformed with x*a/b and inverted with x*b/a
ax1.set_xlim(0.1,10.)
a,b = 1.e37,2.*(3.809e8)
axup = ax1.secondary_xaxis('top',functions=(lambda x: x*a/b,lambda x: x*b/a))

secondary log axis


回调

您可以使用 Axes callbacksax1axup 连接:

[您可以连接到的 Axes 回调] 事件是 xlim_changedylim_changed,回调将使用 func(ax) 调用,其中 ax 是 { {1}} 个实例。

此处 Axes 事件触发 ax1.xlim_changedscale_axup() 缩放为 axup.xlim。请注意,我将 scale(ax1.xlim) 增加到 10 以显示更多主要刻度:

xlim
,

按照您分享的answer,我根据您的需要修改了代码。

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np

from matplotlib.ticker import StrMethodFormatter

fig,6))

ax1.set_ylabel(r'y axis')
ax1.set_xlabel(r'Linear axis')

ax1.set_xlim(0.1,1.5)

#Upper lox-axis
def tick_function(x):
    v = np.log(x*1.e37/(2.*(3.809e8)))
    return ["%.1f" % z for z in v]


axup_locations = np.arange(0.1,10.,0.1)


axup=ax1.twiny()

axup.set_xscale('log')
axup.set_xlim(0.1,100)
axup.set_yscale('linear')
axup.xaxis.set_major_formatter(StrMethodFormatter('{x:.0f}'))


axup.set_xlabel(r'Log axis')
plt.show()

log scale

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?