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='/');
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
?
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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With