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

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

我正在使用 pd.DataFrame.plot() 可视化多个品牌的 %YoY 变化。我不确定如何访问每个单独的子图并将值 >=0 设置为绿色,将 <0 设置为红色。我想避免在 fig, ax 中拆分代码。想知道有没有办法把它包含在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')

我试过使用颜色图,但它没有将各个条设置为不同的颜色,而是将每个子图设置为不同的颜色。我确定我错过了什么。任何帮助表示赞赏。

Example of 2x2 subplots

您可以使用以下策略:

  • 使用 matplotlib 使用 sharey=True
  • 创建一个带有子图的图形对象
  • 遍历 DataFrame 列并将绿色/红色分配给值,如 this 答案
  • 中所示
  • 传递给定的子图以使用 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()

解决如下

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