python - 如何在 matplotlib 中使直方图中的标签居中

标签 python matplotlib

我有以下问题。我需要在 plt.hist() 的 X 轴上将标签居中。我在这里找到了一些答案:How to center labels in histogram plot建议使用 align = "left/mid/right"。但是,它没有给我正确的输出:

plt.hist(数据['Col1'], align='left') enter image description here

plt.hist(数据['Col1'], align='mid') enter image description here

plt.hist(数据['Col1'], align='right') enter image description here

我想让 ok18 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()

visualizing  plt.hist

为了更好地控制离散数据的直方图,最好在给定值附近给出明确的分箱(例如 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()

bar plot with counts

注意 seaborn 的 histplot()更好地处理离散数据。使用字符串或显式设置 discrete=True 时,会自动计算适当的 bin。

关于python - 如何在 matplotlib 中使直方图中的标签居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66152160/

相关文章:

python - 基于变量值的自定义绘图标记

python - 网络抓取中的空 CSV - Python

python - 在 Python 2 或 3 中,如何同时获取系统调用的返回码和返回字符串?

python - 为什么 torch.from_numpy 需要不同的字节顺序而 matplotlib 不需要?

python - 强制所有 x 轴值在 Python 的散点图中进行比较

python - matplotlib/python - 如何绘制这样的图?平均值 ± 3* 标准偏差

javascript - 将绘图中的数据保存到 csv 或 excel 文件中

python - 使用三引号将变量值添加到字符串中

python - 适合 WCS 来治愈

python - 如何可视化集群边界