seaborn如何更改垃圾箱的宽度

2024-10-02 22:33:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个等级表,我希望所有的垃圾箱都在同一个宽度

我希望垃圾箱的范围为[0,56,60,65,70,80,85,90,95100] 当第一个箱子从0-56然后是56-60。。。同宽

sns.set_style('darkgrid') 
newBins = [0,56,60,65,70,80,85,90,95,100]

sns.displot(data= scores  , bins=newBins)

plt.xlabel('grade')
plt.xlim(0,100)
plt.xticks(newBins);

histogram plot with unbalanced bins

不是我要找的:

enter image description here

如何平衡垃圾箱的宽度


Tags: data宽度stylepltgradesetsnsbins
3条回答

你需要欺骗一下。定义您自己的存储箱,并使用线性范围命名存储箱。以下是一个例子:

s = pd.Series(np.random.randint(100, size=100000))
bins = [-0.1, 50, 75, 95, 101]
s2 = pd.cut(s, bins=bins, labels=range(len(bins)-1))
ax = s2.astype(int).plot.hist(bins=len(bins)-
1)
ax.set_xticks(np.linspace(0, len(bins)-2, len(bins)))
ax.set_xticklabels(bins)

输出:

enter image description here

旧答案:

你为什么不让seaborn帮你挑选垃圾箱:

sns.displot(data=scores, bins='auto')

或者设置所需的垃圾箱数量:

sns.displot(data=scores, bins=10)

它们将均匀分布

只需更改用作绑定的值列表:

newBins = numpy.arange(0, 100, 1)

将列表分配给sns.distplot()bins参数。这将指定垃圾箱的边缘。由于这些边缘的间距不均匀,因此箱子的宽度会有所不同

我认为您可能希望使用条形图(sbs.barplot()),而不是直方图。您需要计算每个箱子中有多少个数据点,然后绘制条形图,而不知道每个条形图表示的值的范围。大概是这样的:

import seaborn as sns
import matplotlib.pyplot as plt
sns.set_style('darkgrid') 
import numpy as np

# sample data
data = np.random.randint(0, 100, 200)
newBins = [0,56,60,65,70,80,85,90,95,100]

# compute bar heights
hist, _ = np.histogram(data, bins=newBins)
# plot a bar diagram
sns.barplot(x = list(range(len(hist))), y = hist)
plt.show()

它给出:

enter image description here

相关问题 更多 >