[Matplotlib draws a histogram]

Draw a histogram with Matplotlib

In data analysis and data visualization, a histogram is a common type of chart used to show the distribution of data. Python's Matplotlib library provides us with convenient and easy-to-use functions to draw histograms.

draw histogram

The following code shows how to plot a histogram using Matplotlib, using a random set of data:

import numpy as np
import matplotlib.pyplot as plt

# 生成一组随机数据
data = np.random.normal(0, 1, 1000)

# 绘制直方图
plt.hist(data, bins=20, edgecolor='black')

# 添加标题和标签
plt.title('Histogram of Data')
plt.xlabel('Value')
plt.ylabel('Frequency')

# 显示图形
plt.show()

In the above code, we first imported the required libraries. Then, np.random.normala set of random data was generated using data, where 1000 random numbers were generated using a normal distribution (mean 0, standard deviation 1).

Next, plt.histthe histogram was plotted using the method. plt.histIt accepts multiple parameters, where datais the input data binsand the number of groups in the histogram, which is used to control the number of histograms. We set bins=20, which means dividing the data into 20 groups. edgecolor='black'is to add a black border to the border of each bar graph, increasing the readability of the chart.

Then, title and axis labels are added using the plt.title, plt.xlabeland methods to better understand the contents of the chart.plt.ylabel

Finally, the graph is displayed using plt.show()the method so that the plotted histogram can be viewed in the graph window.

Guess you like

Origin blog.csdn.net/qq_66726657/article/details/131967395