11

How can I apply different hatches to my data, just as I can define different colours as a tuple?

#!/usr/bin/env python3
import pandas
from matplotlib import pyplot as plt

data = {"Label 1": [2,3,5,10], "Label 2": [1,2,4,8]}
pandas.DataFrame(data).plot.bar(color=("grey", "white"), hatch=("/", "*"))
plt.show()

With this code, Hatches apply to all bars altogether.

Hatches are applied altogether to all bars. Instead, I'd rather have each data set using its own hatch-colour combination.

I know that I can manually modify each patch in the plot like this:

ax = pandas.DataFrame(data).plot.bar(color=("grey", "white"), legend=False)
for container, hatch in zip(ax.containers, ("/", "*")):
    for patch in container.patches:
        patch.set_hatch(hatch)
ax.legend(loc='upper center')
plt.show()

Manually set hatch to patches:

This is kind of hacky, but the best solution, I have found via this discussion.

What is the proper way of applying hatches to different data sets in a combined plot?

Paweł Pedryc
  • 368
  • 2
  • 5
  • 19
Pokulo
  • 123
  • 1
  • 11
  • Ok, thanks to @ImportanceOfBeingErnest, edited my post again and probably answered my question good enough on my on. But maybe another better answer emerges. – Pokulo Mar 07 '17 at 12:57
  • 1
    The key-problem was the legend-plotting didn't change when manually setting the hatch of each patch in a container. But after manually disabling and plotting the legend later, its conforming to the hatched colouring as well. – Pokulo Mar 07 '17 at 13:04

1 Answers1

1

You can plot each series individually:

import pandas as pd
from matplotlib import pyplot as plt

data = pd.DataFrame({"Label 1": [2, 3, 5, 10], "Label 2": [1, 2, 4, 8]})
data['Label 1'].plot.bar(legend=True, label='Label 1', color="red", width=-0.2, align='edge', hatch='/')
data['Label 2'].plot.bar(legend=True, label='Label 2', color="green", width=0.2, align='edge', hatch='*')
plt.show()

Resulting plot

Alex Bochkarev
  • 2,851
  • 1
  • 18
  • 32