[英]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.