As shown in the figure below, make a note because you want to plot the cumulative frequency and ratio on the histogram.
When plotting the histogram, you can get the frequency and bin information from the return value of pyplot.hist ()
, so use it to calculate the cumulative ratio on the second axis and overlay it in the appropriate place. The code is below (main part only)
"""Add cumulative ratio to the histogram"""
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# % matplotlib inline
#Plot in seaborn style
sns.set(style="darkgrid", palette="muted", color_codes=True)
#Toy data generation
np.random.seed(0)
dt = np.random.normal(size=100)
fig, ax1 = plt.subplots()
#Histogram plot and bin information acquisition
n, bins, patches = ax1.hist(dt, alpha=0.7, label='Frequency')
#Calculation of values for the 2nd axis
y2 = np.add.accumulate(n) / n.sum()
x2 = np.convolve(bins, np.ones(2) / 2, mode="same")[1:]
#2nd axis plot
ax2 = ax1.twinx()
lines = ax2.plot(x2, y2, ls='--', color='r', marker='o',
label='Cumulative ratio')
ax2.grid(visible=False)
plt.show()
For those who want to add a legend or something here, there is a full version. ~~ How do you do it when using seaborn.FacetGrid ()
~~ I wrote it.
Add cumulative ratio to maplotlib histogram 2 ~ Use FacetGrid ~
Recommended Posts