3

I'm visualizing %YoY change across multiple brands using pd.DataFrame.plot(). I'm unsure how to access each individual subplot and set values >=0 as green and <0 as red. 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().

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

Jolanda
  • 33
  • 4

2 Answers2

0

You can use the following strategy:

  • Create a figure object with subplots using matplotlib using sharey=True
  • Loop over the DataFrame columns and assign Green/ Red colors to the values as shown in this answer
  • Pass a given subplot for plotting a particular column using 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()

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • Thank you. This helped me along. My original question was amended as I was trying to create a 2x2 layout not 1x3. When using the above I ran into the following error: AttributeError: 'numpy.ndarray' object has no attribute 'get_figure'. Found solution here: [github](https://github.com/pandas-dev/pandas/issues/8117) – Jolanda Jun 18 '19 at 09:48
0

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

Jolanda
  • 33
  • 4