Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hatch more than one data serie in a histogram

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?

like image 965
heracho Avatar asked Oct 27 '16 20:10

heracho


People also ask

How do you plot multiple histograms on the same plot?

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.

How do you plot multiple histograms in Seaborn?

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).

How do you plot a histogram with different variables in Python?

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.


1 Answers

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)
like image 85
wflynny Avatar answered Sep 23 '22 22:09

wflynny