【问题标题】:Use matplotlib: plot error bars on two y axes使用 matplotlib:在两个 y 轴上绘制误差线
【发布时间】:2016-03-10 20:03:08
【问题描述】:

我想绘制一个带有 x 和 y 误差线的系列,然后在第二个 y 轴上绘制带有 x 和 y 误差线的第二个系列,所有这些都在同一个子图上。这可以用 matplotlib 完成吗?

import matplotlib.pyplot as plt
plt.figure()
ax1 = plt.errorbar(voltage, dP, xerr=voltageU, yerr=dPU)
ax2 = plt.errorbar(voltage, current, xerr=voltageU, yerr=currentU)
plt.show()

基本上,我想将 ax2 放在第二个轴上,并将刻度放在右侧。

谢谢!

【问题讨论】:

    标签: python matplotlib plot axes errorbar


    【解决方案1】:

    twinx() 是您添加辅助 y 轴的朋友,例如:

    import matplotlib.pyplot as pl
    import numpy as np
    
    pl.figure()
    
    ax1 = pl.gca()
    ax1.errorbar(np.arange(10), np.arange(10), xerr=np.random.random(10), yerr=np.random.random(10), color='g')
    
    ax2 = ax1.twinx()
    ax2.errorbar(np.arange(10), np.arange(10)+5, xerr=np.random.random(10), yerr=np.random.random(10), color='r')
    

    documentation 不多,除了:

    matplotlib.pyplot.twinx(ax=None) 制作共享 x​​ 轴的第二个轴。新轴将覆盖 ax(如果 ax 为 None,则覆盖当前轴)。 ax2 的刻度将放在右侧,并返回 ax2 实例。

    【讨论】:

      【解决方案2】:

      我一直在努力分享 x 轴,但感谢 @Bart 你救了我! 简单的解决方案是使用twiny 而不是twinx

      ax1.errorbar(layers, scores_means[str(epoch)][h,:],np.array(scores_stds[str(epoch)][h,:]))
      
      # Make the y-axis label, ticks and tick labels match the line color.
      ax1.set_xlabel('depth', color='b')
      ax1.tick_params('x', colors='b')
      
      ax2 = ax1.twiny()
      ax2.errorbar(hidden_dim, scores_means[str(epoch)][:,l], np.array(scores_stds[str(epoch)][:,l]))
      ax2.set_xlabel('width', color='r')
      ax2.tick_params('x', colors='r')
      
      fig.tight_layout()
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-12
        • 1970-01-01
        • 2014-07-10
        • 1970-01-01
        • 2021-12-30
        • 2019-03-27
        • 2021-11-13
        • 1970-01-01
        相关资源
        最近更新 更多