[PYTHON] Add cumulative ratio to matplotlib histogram

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


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

Add cumulative ratio to matplotlib histogram
Add cumulative ratio to matplotlib bar chart
Add cumulative ratio to maplotlib histogram 2 ~ Use FacetGrid ~
Histogram with matplotlib
Add diagonal lines (hatch) to heatmap (python, matplotlib)
[Python] How to draw a histogram in Matplotlib
Add convolution to MNIST
Add information to the bottom of the figure with Matplotlib
How to use Matplotlib
How to add color bars in matplotlib bar plot
[Python] How to create a 2D histogram with Matplotlib
How to add new data (lines and plots) using matplotlib
Add / remove kernel to JupyterLab
Add a dictionary to MeCab
The road to download Matplotlib
behavior of matplotlib: histogram normed
Add page number to PDF
Histogram transparent overlay by Matplotlib
Histogram parameter excerpt from matplotlib
Add System to pyenv-win versions
Add user dictionary to MeCab