简体   繁体   English

使用pandas.Dataframe.plot将条形图的颜色调整为红色(负色)和绿色(正色)

[英]Adjust bar subplots colors to red (negative) and green(positive) using pandas.Dataframe.plot

I'm visualizing %YoY change across multiple brands using pd.DataFrame.plot(). 我正在使用pd.DataFrame.plot()可视化多个品牌之间的%YoY变化。 I'm unsure how to access each individual subplot and set values >=0 as green and <0 as red. 我不确定如何访问每个子图并将> = 0的值设置为绿色,<0的值设置为红色。 I'd like to avoid having to split code out in fig, ax. 我想避免不得不在无花果,斧头中拆分代码。 Wondering if there is a way to include it in the parameters of df.plot(). 想知道是否有一种方法可以将其包含在df.plot()的参数中。

data= {'A': [np.nan, -0.5, 0.5], 
       'B': [np.nan, 0.3, -0.3],
       'C': [np.nan, -0.7, 0.7],
       'D': [np.nan, -0.1, 1]}
df = pd.DataFrame(data=data, index=['2016', '2017', '2018'])`
df.plot(kind='bar', subplots=True, sharey=True, layout=(2,2), legend=False,
        grid=False, colormap='RdBu')

I've tried using colormap, but it doesn't set the individual bars in different colors but each subplot. 我尝试使用颜色图,但是它不会将各个条设置为不同的颜色,而是将每个子图设置为不同的颜色。 I'm sure I'm missing something. 我确定我想念什么。 Any help appreciated. 任何帮助表示赞赏。

Example of 2x2 subplots 2x2子图的示例

You can use the following strategy: 您可以使用以下策略:

  • Create a figure object with subplots using matplotlib using sharey=True 使用sharey=True使用matplotlib创建具有子图的图形对象
  • Loop over the DataFrame columns and assign Green/ Red colors to the values as shown in this answer 循环遍历DataFrame列,并将绿色/红色分配给该值, 如此答案所示
  • Pass a given subplot for plotting a particular column using ax=ax 传递给定的子图以使用ax=ax绘制特定列

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

fig, axes = plt.subplots(ncols=3, sharey=True)

data= {'A': [np.nan, -0.5, 0.5], 
       'B': [np.nan, 0.3, -0.3],
       'C': [np.nan, -0.7, 0.7]}
df = pd.DataFrame(data=data, index=['2016', '2017', '2018'])

for ax, col in zip(axes, df.columns):
    df[col].plot(kind='bar', color=(df[col] > 0).map({True: 'g', False: 'r'}), ax=ax)
    ax.set_title(col)
plt.show()

在此处输入图片说明

Solved as follows 解决如下

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=2, sharey=True)

data= {'A': [np.nan, -0.5, 0.5], 
       'B': [np.nan, 0.3, -0.3],
       'C': [np.nan, -0.7, 0.7],
       'D': [np.nan, -1, 1]}
df = pd.DataFrame(data=data, index=['2016', '2017', '2018'])

for i, col in enumerate(df.columns):
     df[col].plot(kind='bar', color=(df[col] > 0).map({True: 'g', False: 'r'}), 
     ax=axes[i // 2][i % 2], sharex=True, sharey=True, grid=False)
axes[i // 2][i % 2].set_title(col)
plt.show()

Example solution 解决方案示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM