When I colored an histogram it accept a list for the different colors, however, for hatching it accept only one value.
This is the code:
import numpy as np
import matplotlib.pylab as plt
data = [np.random.rand(100) + 10 * i for i in range(3)]
ax1 = plt.subplot(111)
n, bins, patches = ax1.hist(data, 20, histtype='bar',
color=['0', '0.33', '0.66'],
label=['normal I', 'normal II', 'normal III'],
hatch= ['', 'o', '/'])
How can I have different hatch for the different series?
For example, to make a plot with two histograms, we need to use pyplot's hist() function two times. Here we adjust the transparency with alpha parameter and specify a label for each variable. Here we customize our plot with two histograms with larger labels, title and legend using the label we defined.
Create two lists (x and y). Create a figure and add a set of two subplots. Iterate a list consisting of x and y. Plot a histogram with histplot() method using the data in the list (step 3).
plt. hist() method is used multiple times to create a figure of three overlapping histograms. we adjust opacity, color, and number of bins as needed. Three different columns from the data frame are taken as data for the histograms.
Unfortunately, it doesn't look like hist supports multiple hatches for multi-series plots. However, you can get around that with the following:
import numpy as np
import matplotlib.pylab as plt
data = [np.random.rand(100) + 10 * i for i in range(3)]
ax1 = plt.subplot(111)
n, bins, patches = ax1.hist(data, 20, histtype='bar',
color=['0', '0.33', '0.66'],
label=['normal I', 'normal II', 'normal III'])
hatches = ['', 'o', '/']
for patch_set, hatch in zip(patches, hatches):
for patch in patch_set.patches:
patch.set_hatch(hatch)
The object patches
returned by hist
is a list of BarContainer
objects, each of which holds a set of Patch
objects (in BarContainer.patches
). So you can access each patch object and set its hatch explicitly.
or as @MadPhysicist pointed out you can use plt.setp
on each patch_set
so the loop can be shortened to:
for patch_set, hatch in zip(patches, hatches):
plt.setp(patch_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