Home > Blockchain >  Colored hatched bar plot on overlapping / hidden bars with matplotlib
Colored hatched bar plot on overlapping / hidden bars with matplotlib

Time:02-11

Currently, I create my bar plot like this to compare two results

plt.figure(figsize=(12,8))
result_df.sym.plot(kind='barh', edgecolor='none')
result_df.non_sym.plot(kind='barh', edgecolor='none',color='orange')

This results in this

enter image description here

I want to show that the blue results generally outperform the yellow ones. But for some categories they do not, so they aren't visible at all. What I now want is something like this:enter image description here

I quickly added this with powerpoint but of course I want to generate it directly with matplotlib/seaborn/pandas. But I have no idea how. There is the hatched parameter in matplotlib but it does not give the effect I want.

CodePudding user response:

With matplotlib you can get this effect by plotting a third bar with the first dataset using only the hatch:

df = pd.DataFrame({'A': [1, 2, 3, 4],
                   'B': [4, 3, 2, 1]
                  })

import matplotlib as mpl
mpl.rcParams['hatch.linewidth'] = 10
mpl.rcParams['hatch.color'] = '#1F77B4'
df['A'].plot(kind='barh', edgecolor='none', color='#1F77B4')
df['B'].plot(kind='barh', edgecolor='none',color='orange')
df['A'].plot(kind='barh', color='none', hatch='/')

output:

hatched plot 1

or

df['A'].plot(kind='barh', edgecolor='none', color='#1F77B4')
df['B'].plot(kind='barh', edgecolor='none',color='orange')
df['A'].mask(df['B'].lt(df['A'])).plot(kind='barh', color='none', hatch='/')

output:

hatched plot 2

For thinner hatches:

import matplotlib as mpl
mpl.rcParams['hatch.linewidth'] = 3
mpl.rcParams['hatch.color'] = '#1F77B4'
df['A'].plot(kind='barh', edgecolor='none', color='#1F77B4')
df['B'].plot(kind='barh', edgecolor='none',color='orange')
df['A'].mask(df['B'].lt(df['A'])).plot(kind='barh', color='none', hatch='//')

output:

thin hatches

CodePudding user response:

sebko_iic. How about just drawing blues right under the yellows, or the yellows under the blues? Just set the right offset in this line: Details: https://scipy-cookbook.readthedocs.io/items/Matplotlib_MultilinePlots.html

  • Related