Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I plot hatched bars using pandas?

I am trying to achieve differentiation by hatch pattern instead of by (just) colour. How do I do it using pandas?

It's possible in matplotlib, by passing the hatch optional argument as discussed here. I know I can also pass that option to a pandas plot, but I don't know how to tell it to use a different hatch pattern for each DataFrame column.

df = pd.DataFrame(rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.plot(kind='bar', hatch='/');

enter image description here

For colours, there is the colormap option described here. Is there something similar for hatching? Or can I maybe set it manually by modifying the Axes object returned by plot?

like image 832
metakermit Avatar asked Apr 03 '14 09:04

metakermit


People also ask

How do you plot a bar graph between two columns in pandas?

Pandas has a tight integration with Matplotlib. You can plot data directly from your DataFrame using the plot() method. To plot multiple data columns in single frame we simply have to pass the list of columns to the y argument of the plot function.


2 Answers

This is kind of hacky but it works:

df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
ax = plt.figure(figsize=(10, 6)).add_subplot(111)
df.plot(ax=ax, kind='bar', legend=False)

bars = ax.patches
hatches = ''.join(h*len(df) for h in 'x/O.')

for bar, hatch in zip(bars, hatches):
    bar.set_hatch(hatch)

ax.legend(loc='center right', bbox_to_anchor=(1, 1), ncol=4)

bar

like image 189
behzad.nouri Avatar answered Sep 21 '22 11:09

behzad.nouri


This code allows you a little more freedom when defining the patterns, so you can have '//', etc.

bars = ax.patches
patterns =('-', '+', 'x','/','//','O','o','\\','\\\\')
hatches = [p for p in patterns for i in range(len(df))]
for bar, hatch in zip(bars, hatches):
    bar.set_hatch(hatch)
like image 33
Leonardo Avatar answered Sep 20 '22 11:09

Leonardo