1

I was wondering if it possible to achieve so that error bars are made white with a black border (in a Pandas bar plot)?

I am trying to achieve what is mentioned in the accepted answer in this post (Border on errorbars in matplotlib/python), however I am wondering if it is possible to implement this for a Pandas plot?

The relevant Pandas plot:

from io import StringIO
import pandas as pd
import matplotlib.pyplot as plt

txt = u'''Category    COLUMN1         COLUMN2     COLUMN3    
A          0.5               3          Cat1   
B          0.3               5          Cat1 
C          0.7               4          Cat1
A          0.4               3          Cat2
B          0.8               5          Cat2
C          0.3               4          Cat2
'''

df = pd.read_table(StringIO(txt), sep="\s+")

order = ['Cat2', 'Cat1']
suborder = list("BAC")

df2 = pd.pivot_table(df,index='COLUMN3',columns='Category',values='COLUMN2').loc[order]
df2 = df2[suborder]
df2.plot(kind='bar', 
         yerr=pd.pivot_table(df,
                             index='COLUMN3',
                             columns='Category',values='COLUMN1')
                .reindex(df2.index)
                .reindex(df2.columns, axis=1), capsize=4)

1 Answers1

1

You can basically use the same principle as shown in the answer you link to, with some slight modifications as you are using pandas rather than pure matplotlib. The idea is the same, to plot the graph twice, and on the second time use slightly thicker errorbars and set the zorder lower which we can do using a dictionary of kwargs - error_kw . In addition, make sure to pass the ax= argument too in order to make sure the plots appear on the same figure and set legend=False on the second plot to avoid repeating legend entries.

fig, ax = plt.subplots()

df2.plot(kind='bar', 
         yerr=pd.pivot_table(df,
                             index='COLUMN3',
                             columns='Category',values='COLUMN1')
                .reindex(df2.index)
                .reindex(df2.columns, axis=1), ax=ax,
                error_kw=dict(ecolor='white', capthick=2,elinewidth=2,capsize=3,zorder=10))


df2.plot(kind='bar', 
         yerr=pd.pivot_table(df,
                             index='COLUMN3',
                             columns='Category',values='COLUMN1')
                .reindex(df2.index)
                .reindex(df2.columns, axis=1), ax=ax, legend=False,
                error_kw=dict(ecolor='black',capthick=4,elinewidth=4,capsize=4,zorder=5))

enter image description here

DavidG
  • 24,279
  • 14
  • 89
  • 82