📜  如何从 Matplotlib 中的数据列表中绘制直方图?

📅  最后修改于: 2022-05-13 01:55:14.177000             🧑  作者: Mango

如何从 Matplotlib 中的数据列表中绘制直方图?

在本文中,我们将了解如何在Python中从 Matplotlib 中的数据列表中绘制直方图。

直方图帮助我们绘制带有指定 bin 的条形图,并且可以使用 hist()函数创建。

示例 1:

在此示例中,我们将列表传递给 hist 方法以从数据列表中绘制直方图。这里我们没有在 hist 方法中指定 edgecolor 和 bins 参数。所以在上面的输出中,我们没有找到任何条的任何边缘颜色,我们得到了随机数量的箱(条)。

Python3
# import necessary packages
import matplotlib.pyplot as plt
 
# list of weights
weights = [30, 50, 45, 80, 76, 55,
           45, 47, 50, 65]
 
# plotting labelled histogram
plt.hist(weights)
plt.xlabel('weight')
plt.ylabel('Person count')
plt.show()


Python3
# import necessary packages
import matplotlib.pyplot as plt
 
# list of weights
weights = [30, 50, 45, 80, 76, 55,
           45, 47, 50, 65]
 
# plotting labelled histogram
plt.hist(weights, bins=5, edgecolor='black')
plt.xlabel('weight')
plt.ylabel('Person count')
plt.show()


Python3
# import necessary packages
import matplotlib.pyplot as plt
 
# list of weights
weights = [30, 50, 45, 80, 76, 55,
           45, 47, 50, 65]
 
# list of bins
bins = [30, 40, 50, 60]
 
# plotting labelled histogram
plt.hist(weights, bins=bins, edgecolor='black')
plt.xlabel('weight')
plt.ylabel('Person count')
plt.show()


输出:

示例 2:

对于我们在上面示例中使用的相同数据,我们将在此示例中另外指定 bin 和 edgecolor。

Python3

# import necessary packages
import matplotlib.pyplot as plt
 
# list of weights
weights = [30, 50, 45, 80, 76, 55,
           45, 47, 50, 65]
 
# plotting labelled histogram
plt.hist(weights, bins=5, edgecolor='black')
plt.xlabel('weight')
plt.ylabel('Person count')
plt.show()

输出:

当我们将 bin 计数指定为 5 时,我们在结果图中得到了 5 个条形图,并且 edgecolor 帮助我们区分它们之间的条形图,如果它们像上述场景中那样彼此靠近。

示例 3:

我们还可以将值列表作为参数传递给 hist 方法中的 bins 参数。它可以帮助我们过滤列表中的数据。

Python3

# import necessary packages
import matplotlib.pyplot as plt
 
# list of weights
weights = [30, 50, 45, 80, 76, 55,
           45, 47, 50, 65]
 
# list of bins
bins = [30, 40, 50, 60]
 
# plotting labelled histogram
plt.hist(weights, bins=bins, edgecolor='black')
plt.xlabel('weight')
plt.ylabel('Person count')
plt.show()

输出:

由于我们将包含 30、40、50、60 的 bin 列表传递给 bins 参数,因此在从数据列表绘制直方图时, Python仅考虑指定 bin 范围内的数据。因此,如果数据值超出范围,则在绘图时不考虑该数据点。

在给定的数据列表中,65、76、80 超出了 bin 范围,因此,在绘制图表期间不考虑这些数据点。