import numpy as np
## Generate 1000 data points from a normal distribution
## with a mean (loc) of 0 and a standard deviation (scale) of 1.
data = np.random.normal(loc=0, scale=1, size=1000)
print("Sample data generated successfully.")
要运行脚本,请在 WebIDE 中打开终端(Terminal -> New Terminal),然后执行以下命令。你的工作目录已经是 /home/labex/project。
import numpy as np
import matplotlib.pyplot as plt
## Generate sample data
data = np.random.normal(loc=0, scale=1, size=1000)
## Create a histogram
plt.hist(data)
## Save the plot to a file
plt.savefig('/home/labex/project/histogram.png')
print("Basic histogram saved to histogram.png")
在本步骤中,你将学习如何通过设置 bin 的数量来控制直方图的粒度。“bin”是一个表示数据范围的区间。bin 的数量会显著影响对分布的解读。过少的 bin 可能会隐藏重要细节,而过多的 bin 则可能导致绘图噪点过多。
Matplotlib 的 plt.hist() 函数有一个 bins 参数,允许你指定 bin 的数量。默认情况下,Matplotlib 会选择一个合理的数量,但你通常需要调整它。
让我们修改代码,创建一个包含 30 个 bin 的直方图。我们还将它保存到一个新文件 histogram_bins.png,以便与之前的绘图进行比较。
按以下方式更新你的 main.py 文件:
import numpy as np
import matplotlib.pyplot as plt
## Generate sample data
data = np.random.normal(loc=0, scale=1, size=1000)
## Create a histogram with 30 bins
plt.hist(data, bins=30)
## Save the plot to a new file
plt.savefig('/home/labex/project/histogram_bins.png')
print("Histogram with 30 bins saved to histogram_bins.png")
在终端中运行脚本:
python3 main.py
输出将是:
Histogram with 30 bins saved to histogram_bins.png
import numpy as np
import matplotlib.pyplot as plt
## Generate sample data
data = np.random.normal(loc=0, scale=1, size=1000)
## Create a histogram with 30 bins, custom color, and edgecolor
plt.hist(data, bins=30, color='skyblue', edgecolor='black')
## Save the plot to a new file
plt.savefig('/home/labex/project/histogram_color.png')
print("Styled histogram saved to histogram_color.png")
在本步骤中,你将学习如何创建归一化直方图。默认情况下,直方图的 y 轴表示每个 bin 中的数据点数量。然而,有时将分布视为概率密度会更有用。在归一化直方图中,每个条形的高度会进行调整,使得所有条形的总面积等于 1。
这可以通过在 plt.hist() 函数中将 density 参数设置为 True 来实现。同时,为绘图添加标签和标题,使其具有自解释性也是一个好习惯。
让我们更新脚本以创建归一化直方图并添加描述性标签。
import numpy as np
import matplotlib.pyplot as plt
## Generate sample data
data = np.random.normal(loc=0, scale=1, size=1000)
## Create a normalized histogram
plt.hist(data, bins=30, color='skyblue', edgecolor='black', density=True)
## Add title and labels
plt.title('Normalized Histogram of Sample Data')
plt.xlabel('Value')
plt.ylabel('Probability Density')
## Save the plot to a new file
plt.savefig('/home/labex/project/histogram_normalized.png')
print("Normalized histogram saved to histogram_normalized.png")
运行脚本的最终版本:
python3 main.py
输出将是:
Normalized histogram saved to histogram_normalized.png