我有兩個由以下代碼生成的相互重疊的圖:
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)。如何在不更改條形圖的情況下定義它?
uj5u.com熱心網友回復:
當您呼叫 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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/371225.html
標籤:Python 熊猫 matplotlib
