【问题标题】:X-ticks do not match defined bins in plotX-ticks 与图中定义的 bin 不匹配
【发布时间】:2025-12-24 12:30:12
【问题描述】:

我正在使用 Seaborn 的 FacetGrid 绘制多个带有预定义箱的 matplotlib.pyplot.hist 图。我希望它显示 X-tick 标签。

根据我阅读的内容,我正在尝试:

bins = [0,3,6,9,12,15,18,21,24,30,40,50,60,80]
g = sns.FacetGrid(allData, col="Survived", row="Sex")
g = g.map(plt.hist, "Age", bins=bins)
g.set_xticklabels(bins)

刻度与我预期的方式不匹配;我原以为每个条都是一个“bin”,所以第一个条是:[0-3],第二个:[3-6],等等。相反,每个刻度都跨越多个条。 (正在使用泰坦尼克号数据集)。

我基本上希望每个标有年龄范围的条都代表。我不确定我要去哪里错,任何帮助将不胜感激。

【问题讨论】:

  • 永远不要只设置标签,而不定义它们的位置。 IE。在不使用set_ticks 的情况下,切勿使用set_xticklabels。否则 matplotlib 会知道要使用哪些标签,但不知道将它们放在哪里。

标签: matplotlib seaborn


【解决方案1】:

这里是一个例子(.set(xticks=bins):

bins = [0,3,6,9,12,15,18,21,24,30,40,50,60,80]
g = sns.FacetGrid(allData, col="Survived", row="Sex", size=8) 
g = (g.map(plt.hist, "Age", bins=bins)).set(xticks=bins)

【讨论】:

  • 谢谢,我原以为它会将每个范围视为一个类别并具有固定宽度,但我认为这可以追溯到 @ImportanceOfBeingErnest 提到的刻度和标签之间的差异。跨度>
【解决方案2】:

我从未使用过 sns,在 matplotlib 中我可以更好地控制绘图,尽管需要更多的输入。

import numpy as np
import matplotlib.pyplot as plt


def fun():
    mu, sigma = 100, 15
    x = mu + sigma * np.random.randn(100)
    return x


fig, ax = plt.subplots(2,2, sharex=True, figsize=(14, 8))

binned = list(range(50, 160, 10))

ax[0,0].hist(fun(), binned, density=True, facecolor='g', alpha=0.75)
ax[0,0].set_title('Sex = male | survived = 0')
ax[0,1].hist(fun(), binned, density=True, facecolor='g', alpha=0.75)
ax[0,1].set_title('Sex = male | survived = 1')
ax[1,0].hist(fun(), binned, density=True, facecolor='g', alpha=0.75)
ax[1,0].set_title('Sex = female | survived = 0')
ax[1,1].hist(fun(), binned, density=True, facecolor='g', alpha=0.75)
ax[1,1].set_title('Sex = female | survived = 1')



for col in ax:
    for row in col:
        if row.axes.rowNum == 1:
            row.set_xlabel('age')
        row.locator_params(axis='x', nbins=15)
        row.spines['right'].set_visible(False)
        row.spines['top'].set_visible(False)
        row.grid()
plt.show()

【讨论】: