Matplotlib 的hist() 带有默认参数,主要用于连续数据。
当没有给定参数时,matplotlib 将值的范围划分为 10 个大小相等的 bin。
当给定字符串数据时,matplotlib 在内部用数字0, 1, 2, ... 替换字符串。在这种情况下,“ok”得到值0,而“18 let”得到值1。将该范围划分为 10,创建 10 个箱:0.0-0.1, 0.1-0.2, ..., 0.9-1.0。条形图放置在 bin 中心 (0.05, 0.15, ..., 0.95) 并默认对齐 'mid'。 (当您想要绘制较窄的条时,这种居中会有所帮助。)在这种情况下,除了第一个和最后一个条之外的所有条都将具有高度 0。
这是正在发生的事情的可视化。垂直线显示 bin 边界的放置位置。
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
data = pd.DataFrame({'Col1': np.random.choice(['ok', '18 let'], 10, p=[0.2, 0.8])})
plt.style.use('ggplot')
fig, ax = plt.subplots()
ax.locator_params(axis='y', integer=True)
ax.set_ylabel('Frequency', fontweight='bold')
_counts, bin_boundaries, _patches = ax.hist(data['Col1'])
for i in bin_boundaries:
ax.axvline(i, color='navy', ls='--')
ax.text(i, 1.01, f'{i:.1f}', transform=ax.get_xaxis_transform(), ha='center', va='bottom', color='navy')
plt.show()
为了更好地控制离散数据的直方图,最好给出明确的 bin,很好地围绕给定的值(例如 plt.hist(..., bins=[-0.5, 0.5, 1.5]))。更好的方法是创建计数图:计算单个值并绘制条形图(直方图只是一种特定类型的条形图)。
以下是此类“计数图”的示例。 (请注意,numpy 的np.unique() 的return_counts= 参数仅适用于较新的版本,1.9 及更高版本。)
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
data = pd.DataFrame({'Col1': np.random.choice(['ok', '18 let'], 10, p=[0.2, 0.8])})
plt.style.use('ggplot')
plt.locator_params(axis='y', integer=True)
plt.ylabel('Frequency', fontweight='bold')
labels, counts = np.unique(data['Col1'], return_counts=True)
plt.bar(labels, counts)
plt.show()
请注意,seaborn 的 histplot() 可以更好地处理离散数据。使用字符串或显式设置 discrete=True 时,会自动计算相应的 bin。