【问题标题】:Change y axis range of a secondary axis in python Matplotlib在 python Matplotlib 中更改辅助轴的 y 轴范围
【发布时间】:2021-11-30 14:55:37
【问题描述】:

我有两个由以下代码生成的相互重叠的图:

import matplotlib.pyplot as plt
import pandas as pd

width=.5
t=pd.DataFrame({'bars':[3.4,3.1,5.1,5.1,3.8,4.2,5.2,4.0,3.6],'lines':[2.4,2.2,2.4,2.1,2.0,2.1,1.9,1.8,1.9]})
t['bars'].plot(kind='bar',width=width)
t['lines'].plot(secondary_y=True, color='red')

ax=plt.gca()
plt.xlim([-width,len(t['bars'])-width])
ax.set_xticklabels(('1','2','3','4','5','6','7','8','9'))
plt.show()

我希望能够以 0.5 的步长将第二个 y 轴的范围从 0.0 扩展到 2.5(而不是 1.8 到 2.4)。如何在不更改条形图的情况下定义它?

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    当你调用 plot 函数时,Pandas 返回它绘制的轴。只需保存该轴并使用面向对象的方法修改限制即可。

    import matplotlib.pyplot as plt
    import pandas as pd
    
    width=.5
    
    t=pd.DataFrame({'bars':[3.4,3.1,5.1,5.1,3.8,4.2,5.2,4.0,3.6],'lines':[2.4,2.2,2.4,2.1,2.0,2.1,1.9,1.8,1.9]})
    ax1 = t['bars'].plot(kind='bar',width=width)
    ax2 = t['lines'].plot(secondary_y=True, color='red')
    
    ax2.set_ylim(0, 2.5)
    
    ax1.set_xlim([-width,len(t['bars'])-width])
    ax1.set_xticklabels(('1','2','3','4','5','6','7','8','9'))
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2013-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-28
      • 2015-09-14
      • 2018-12-11
      • 2020-11-26
      • 2016-02-26
      相关资源
      最近更新 更多