Python: align bars between bin edges for double histogram
I am having a problem using pyplot.hist function to plot two histograms in the same figure. For each interning interval, I want 2 columns to be centered between the bins (Python 3.6 user). To illustrate this, here's an example:
import numpy as np
from matplotlib import pyplot as plt
bin_width=1
A=10*np.random.random(100)
B=10*np.random.random(100)
bins=np.arange(0,np.round(max(A.max(),B.max())/bin_width)*bin_width+2*bin_width,bin_width)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.hist(A,bins,color='Orange',alpha=0.8,rwidth=0.4,align='mid',label='A')
ax.hist(B,bins,color='Orange',alpha=0.8,rwidth=0.4,align='mid',label='B')
ax.legend()
ax.set_ylabel('Count')
I get this:
The A and B series overlap, which is not good. Knowing that there are only 3 options for "leveling" (center left of the left bin, from the middle of the 2 bins, center in the right cell), I don't see any other options other than changing the bins by adding:
bins-=0.25*bin_width
Before building A and adding:
bins+=0.5*bin_width
Before plotting B. This gives me: Histogram
This is better! However, I had to modify binning so it is not the same for A and B.
I was looking for an easy way to use the same boxes and then swap the 1st and 2nd parcels so that they appear correctly in the swap intervals, but I couldn't find one. Any advice?
Hope I have explained my problem clearly.
source to share
As mentioned above, you don't need the plotting function. Use numpy histogram function and write it with matplotlib's bar function.
According to the number of bins and the number of data types, you can calculate the bin width. The pliers you can customize with the xticks method:
import numpy as np
import matplotlib.pylab as plt
A=10*np.random.random(100)
B=10*np.random.random(100)
bins=20
# calculate heights and bins for both lists
ahist, abins = np.histogram(A, bins)
bhist, bbins = np.histogram(B, abins)
fig = plt.figure()
ax = fig.add_subplot(111)
# calc bin width for two lists
w = (bbins[1] - bbins[0])/3.
# plot bars
ax.bar(abins[:-1]-w/2.,ahist,width=w,color='r')
ax.bar(bbins[:-1]+w/2.,bhist,width=w,color='orange')
# adjsut xticks
plt.xticks(abins[:-1], np.arange(bins))
plt.show()
source to share