我有以下问题。我需要在 plt.hist() 的 X 轴上将标签居中。我在这里找到了一些答案:How to center labels in histogram plot建议使用 align = "left/mid/right"
。但是,它没有给我正确的输出:
plt.hist(数据['Col1'], align='left')
plt.hist(数据['Col1'], align='mid')
plt.hist(数据['Col1'], align='right')
我想让 ok
和 18 let
恰好位于每个小节的中间。请问我该如何解决?
完整代码:
plt.style.use('ggplot')
plt.xticks(rotation='vertical')
plt.locator_params(axis='y', integer=True)
plt.suptitle('My histogram', fontsize=14, fontweight='bold')
plt.ylabel('Frequency', fontweight='bold')
plt.hist(data['Col1'], align='mid')
plt.show()
最佳答案
Matplotlib 的带有默认参数的hist()
主要用于连续数据。
当没有给定参数时,matplotlib 将值的范围划分为 10 个大小相等的 bin。
当给定字符串数据时,matplotlib 在内部用数字 0, 1, 2, ...
替换字符串。在本例中,“ok”获得值 0
,“18 let”获得值 1
。将该范围分成 10,创建 10 个 bin: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()
为了更好地控制离散数据的直方图,最好在给定值附近给出明确的分箱(例如 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。
关于python - 如何在 matplotlib 中使直方图中的标签居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66152160/