Python 3:使用FuncFormatter

我创建了一个具有两个y轴且共享一个x轴的图形。 y轴彼此相关:左y轴的值是方程式的输入,该方程式给出了右y轴的值。为了使两者相互关联,我将每个轴上的y刻度设置为相同。然后,我尝试使用函数(myticks)使用set_major_formatter(ticker.FuncFormatter(myticks))在适当的标签上标记每个轴上的y刻度。 y刻度在每个轴上的正确位置,标签在左侧的轴上正确,但是标签在右侧的轴上错误。由于某些原因,左轴标签也会显示在右轴上。右轴的值应为right_y2中存在的值。我是Python的新手,所以非常感谢您的帮助!

#plot
fig = plt.figure(figsize=(3,4))
ax1 = fig.add_subplot(111)

y =[1.9E19,1E20,5E20,1.8E21,1E22,1.9E22,1.15E23]
ax1.plot(2,y[0],marker='o')
ax1.plot(2,y[1],y[2],y[3],y[4],y[5],y[6],marker='o')
ax1.set_yscale("log")
ax1.set_ylim(1E19,2E23)
ax1.set_yticks(y)

def myticks(left_y,y):
    exponent = int(np.log10(left_y))
    coeff = left_y/10**exponent
    return r"${:2.0f} \times 10^{{ {:2d} }}$".format(coeff,exponent)

ax1.yaxis.set_major_formatter(ticker.FuncFormatter(myticks))

ax2 = ax1.twinx()
ax2.set_yscale("log")
ax2.set_ylim(1E19,2E23)
ax2.set_yticks(y)


def myticks2(right_y2,y):
    exponent2 = int(np.log10(right_y2))
    coeff2 = right_y2/10**exponent2
    return r"${:2.0f} \times 10^{{ {:2d} }}$".format(coeff2,exponent2)

ax2.yaxis.set_major_formatter(ticker.FuncFormatter(myticks2)

其中

left_y =[1.9E19,1.15E23]
right_y2 =[5.3E12,3.8E13,1.3E14,2.7E14,5E14,9.6E14,3E15]

我得到下图: enter image description here

weiyi961013 回答:Python 3:使用FuncFormatter

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2315458.html

大家都在问