[英]How to center labels in histogram in matplotlib
我有以下问题。 我需要在我的 plt.hist() 上将 X 轴上的标签居中。 我在这里找到了一些答案: How to center labels in histogram plot建议使用align = "left/mid/right"
。 但是,它并没有给我正确的 output:
plt.hist(data['Col1'], align='left')
plt.hist(data['Col1'], align='mid')
plt.hist(data['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()
为了更好地控制离散数据的直方图,最好给出明确的 bin,很好地围绕给定的值(例如plt.hist(..., bins=[-0.5, 0.5, 1.5])
)。 更好的方法是创建计数 plot:计算各个值并绘制条形 plot(直方图只是一种特定类型的条形图)。
这是这种“计数图”的示例。 (请注意,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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.