Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib: assigning different hatch to bars

I have a dataframe where for each index, I have to plot two bars (for two series). The following code gives the output as:

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

df = pd.DataFrame(np.random.randint(0,20,size=(5, 2)), columns=list('AB'))
fig, ax = plt.subplots()
ax = df.sort_values('B', ascending=True).plot.barh(rot=0,ax=ax,hatch="/")
plt.show()

enter image description here

I would like to assign individual hatching for each bar. So that if A has '/' hatching, B should have '|'. What modifications do I need to make in the code?

like image 420
SaadH Avatar asked Apr 24 '19 08:04

SaadH


1 Answers

You can plot the two bars separately:

import numpy as np
import pandas as pd

from matplotlib import pyplot as plt

df = pd.DataFrame(np.random.randint(0, 20, size=(5, 2)), columns=list('AB'))
fig, ax = plt.subplots()

ax.barh(np.arange(0, len(df)), df['A'], height=0.3, hatch='/')
ax.barh(np.arange(0.3, len(df) + 0.3), df['B'], height=0.3, hatch='|')

enter image description here

like image 157
gmds Avatar answered Sep 24 '22 01:09

gmds