[PYTHON] In matplotlib, set the vertical axis on the left side of the histogram to frequency and the vertical axis on the right side to relative frequency (maybe a wicked way)

What to do in this article

This is the sequel to this article. com / kanedaq / items / 1e7a0e52363224c08980)

Histogram with matplotlib

--The vertical axis on the left is the frequency (default of matplotlib) --The vertical axis on the right is the relative frequency (total height of columns = 1)

And draw. However, it may be an evil way.

Reference page (Thank you)

[python] How to draw a graph with two axes on the left and right with matplotlib

Source code (Jupyter Notebook) and drawing results

The number of data is 7,500, and it is a normal random number with an average value of 50 and a standard deviation of 10. First, try running the following Python code.


#%%

import numpy as np
import matplotlib.pyplot as plt


#%%

#Data creation
μ = 50
σ = 10
data = [ np.random.normal(μ, σ) for i in range(7500) ]


#%%

#Number of classes
num_bins = 20

#Graph drawing
fig = plt.figure(figsize=(12, 8))
plt.legend()
plt.xlabel('x', fontsize=18)
plt.title('null', fontsize=18)

# (1)Histogram with frequency on the vertical axis
ax1 = fig.add_subplot(111)
ax1.set_ylabel('frequency', fontsize=18)
ax1.grid(True, color="dimgray")
ax1.set_axisbelow(True)    #Move grid to the back
ax1.hist(data, bins=num_bins, rwidth=0.5, align="mid")

# (2)Histogram with relative frequency on the vertical axis
ax2 = ax1.twinx()
ax2.set_ylabel('relative frequency', fontsize=18)
ax2.grid(True, color="lightgrey", linestyle="--")
ax2.set_axisbelow(True)    #Move grid to the back
weights = np.ones_like(data) / len(data)
ax2.hist(data, bins=num_bins, weights=weights, rwidth=0.5, align="right", color="red")

1.png

The vertical axis = frequency column is drawn in the default color, and the vertical axis = relative frequency column is drawn in red, side by side. People confirm that the heights of both of them look the same </ font> (The reason why they are evil ...)

If the heights of the columns of frequency and relative frequency look the same, match the colors of the columns. Call ax2.hist () without specifying "color =" red "".

2.png

The Grid line of ax2 is displayed in front of the pillar of ax1. To make this horizontal line invisible, I decided to add the following code to overwrite the same graph as ax1.


# (3) (1)Adjust the appearance of
ax3 = ax1.twinx()
ax3.set_yticklabels([]) 
ax3.hist(data, bins=num_bins, rwidth=0.5, align="mid")

3.png

The entire code for the finished version is below.


#%%

import numpy as np
import matplotlib.pyplot as plt


#%%

#Data creation
μ = 50
σ = 10
data = [ np.random.normal(μ, σ) for i in range(7500) ]


#%%

#Number of classes
num_bins = 20

#Graph drawing
fig = plt.figure(figsize=(12, 8))
plt.legend()
plt.xlabel('x', fontsize=18)
plt.title('null', fontsize=18)

# (1)Histogram with frequency on the vertical axis
ax1 = fig.add_subplot(111)
ax1.set_ylabel('frequency', fontsize=18)
ax1.grid(True, color="dimgray")
ax1.set_axisbelow(True)    #Move grid to the back
ax1.hist(data, bins=num_bins, rwidth=0.5, align="mid")

# (2)Histogram with relative frequency on the vertical axis
ax2 = ax1.twinx()
ax2.set_ylabel('relative frequency', fontsize=18)
ax2.grid(True, color="lightgrey", linestyle="--")
ax2.set_axisbelow(True)    #Move grid to the back
weights = np.ones_like(data) / len(data)
ax2.hist(data, bins=num_bins, weights=weights, rwidth=0.5, align="right")

# (3) (1)Adjust the appearance of
ax3 = ax1.twinx()
ax3.set_yticklabels([]) 
ax3.hist(data, bins=num_bins, rwidth=0.5, align="mid")

It feels like an evil way, so please let me know if there is a straightforward approach.

Recommended Posts

In matplotlib, set the vertical axis on the left side of the histogram to frequency and the vertical axis on the right side to relative frequency (maybe a wicked way)
Set the vertical axis of the histogram to relative frequency (total height of columns = 1) and relative frequency density (area of the entire histogram = 1) with matplotlib.
Precautions when drawing the probability density function and the histogram on top of each other in matplotlib
I want to create a histogram and overlay the normal distribution curve on it. matplotlib edition
Grid display of double plots (left and right vertical axes) (matplotlib)
Why put a slice on the left side in the substitution formula
Upload data to s3 of aws with a command and update it, and delete the used data (on the way)
Set the number of elements in a NumPy one-dimensional array to a power of 2 (0 padded)
How to count the number of elements in Django and output to a template
Use libsixel to output Sixel in Python and output a Matplotlib graph to the terminal.
I want to set a life cycle in the task definition of ECS
When the axis and label overlap in matplotlib
Put the second axis in 2dhistgram of matplotlib
The and operator of Python's evaluation expression seems to be evaluated from the left side expression
[Mac] A super-easy way to execute system commands in Python and output the results
A memo to visually understand the axis of pandas.Panel
Write a log-scale histogram on the x-axis in python
Now in Singapore The story of creating a LineBot and wanting to do a memorable job
The vertical and horizontal axes of the matplotlib histogram are unpleasant, so make it feel good
[Golang] Command to check the supported GOOS and GOARCH in a list (Check the supported platforms of the build)
How to quickly count the frequency of appearance of characters from a character string in Python?
An easy way to view the time taken in Python and a smarter way to improve it
Examples and countermeasures for "A value is trying to be set on a copy of a slice from a Data Frame." Warning in pandas
How to send a file in one shot by connecting to a host on the other side of the platform with SCP in multiple stages