Matplotlib Bar Chart choose color if value is positive vs value is negative

前端 未结 4 2086
[愿得一人]
[愿得一人] 2020-11-28 11:02

I have a pandas DataFrame with positive and negative values as a bar chart. I want to plot the positive colors \'green\' and the negative values \'red\' (very original...lol

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 11:47

    Define

    def bar_color(df,color1,color2):
        return np.where(df.values>0,color1,color2).T
    

    then

    data.plot.barh(color=bar_color(data,'r','g'))
    

    gives

    It also works for multiple bar series

    df=pd.DataFrame(np.random.randint(-10,10,(4,6)))
    df.plot.barh(color=bar_color(df,'r','g'))
    

    gives

提交回复
热议问题