【问题标题】:How to center labels in histogram in matplotlib如何在matplotlib的直方图中居中标签
【发布时间】:2021-02-11 09:40:47
【问题描述】:

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

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()

【问题讨论】:

  • 代码?看起来你做对了,但是你有一个额外的垃圾箱并且会导致对齐失败。
  • 我放下面了,谢谢回复

标签: python matplotlib


【解决方案1】:

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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多