[英]Negative values bars on the same matplotlib chart
我正在嘗試在同一圖上顯示3個條形圖。 但是,具有負值的條存在一個問題,因為它們從頂部懸垂或從無處垂下。 有什么想法可以使它看起來更好嗎?
import pandas as pd
import matplotlib.pyplot as plt
x = range(6)
a1 = [-1, -4, -3, -6, 2, 8]
a2 = [ 4, 12, 8, 1, 10, 9]
a3 = [100, 110, 120, 130, 115, 110]
df = pd.DataFrame(index=x,
data={'A': a1,
'B': a2,
'C': a3})
fig, ax = plt.subplots()
ax2 = ax.twinx()
ax3 = ax.twinx()
ax3.spines["right"].set_position(("axes", 1.1))
df['A'].plot(ax=ax, kind='bar', color='blue', width=0.2, position=2)
df['B'].plot(ax=ax2, kind='bar', color='green', width=0.2, position=1)
df['C'].plot(ax=ax3, kind='bar', color='red', width=0.2, position=0)
您可以做一些事情來使它更具可讀性。 您的大問題是,您擁有3個獨立的y軸,因此很難分辨出哪個變量指向哪個變量,並且變量0線(從其定義條形)都很難識別。 您可以通過更改軸顏色以適合您的數據來首先提高可讀性。 然后,您要為所有y軸設置限制,以使它們的零線相同,並使用一些乘法因子來調整比例。 不過請務必小心,因為這可能會誤導讀者,因為它們依賴於將“ A”與“ B”與“ C”進行比較的物理意義。
import pandas as pd
import matplotlib.pyplot as plt
x = range(6)
a1 = [-1, -4, -3, -6, 2, 8]
a2 = [ 4, 12, 8, 1, 10, 9]
a3 = [100, 110, 120, 130, 115, 110]
df = pd.DataFrame(index=x,
data={'A': a1,
'B': a2,
'C': a3})
fig, ax = plt.subplots()
ax2 = ax.twinx()
ax3 = ax.twinx()
ax3.spines["right"].set_position(("axes", 1.1))
df['A'].plot(ax=ax, kind='bar', color='blue', width=0.2, position=2)
df['B'].plot(ax=ax2, kind='bar', color='green', width=0.2, position=1)
df['C'].plot(ax=ax3, kind='bar', color='red', width=0.2, position=0)
#Set the limits based off your negative bar graph then multiply those by some factor
ax.set_ylim(df['A'].min()*1.1,df['A'].max()*1.1)
ax2.set_ylim(df['A'].min()*2,df['A'].max()*2)
ax3.set_ylim(df['A'].min()*20,df['A'].max()*20)
#Change color of axis to make more readable
ax.tick_params(axis='y',color='blue',labelcolor='blue')
ax2.tick_params(axis='y',color='green',labelcolor='green')
ax3.tick_params(axis='y',color='red',labelcolor='red')
#Also add a limit to the x-axis to
ax.set_xlim(-0.5)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.