如何解决绘制上对数轴作为下线性轴的函数 次轴回调
我想绘制一个带有线性 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 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))
回调
您可以使用 Axes callbacks 将 ax1
与 axup
连接:
[您可以连接到的 Axes
回调] 事件是 xlim_changed
和 ylim_changed
,回调将使用 func(ax)
调用,其中 ax
是 { {1}} 个实例。
此处 Axes
事件触发 ax1.xlim_changed
将 scale_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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。