Negative values bars on the same matplotlib chart

喜欢而已 提交于 2021-01-28 04:33:20

问题


I am trying to display 3 bar charts on the same plot. There is an issue with bars that have negative values though, because they are hanging down either from the top or from nowhere. Any ideas how to make it look nicer?

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)


回答1:


There are a couple things you can do to make this more readable. Your big issue is that you have 3 separate y-axis so that its both hard to discern which goes to which variable and you have a variable zero line (which the bars are defined from). You can help the readability first by changing the axis colors to fit your data. Then you want to set your limits for all your y-axis so that they the zero line is the same and use some multiplication factor to then adjust your scales. Be careful though because this could mislead readers dependent on the physical significance of comparing 'A' to 'B' to '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()



来源:https://stackoverflow.com/questions/57628646/negative-values-bars-on-the-same-matplotlib-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!