密度分布和x和y数据的条形图

2024-04-27 10:02:10 发布

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

我在熊猫数据框中有以下数据集:

x = df_data.iloc[:,0].values
y = df_data.iloc[:,1].values

以下数据分别以x和y表示:

x = 30, 31, 32, 33, 34, 35, 36
y = 1000, 2000, 3000, 4000, 3000, 2000, 1000

y表示计数(每个x值存在的频率)

我现在想用密度分布线做一个条形图。我愿意使用seaborn或matplotlib,但找不到单独输入x和y数据以及获得条形图和密度图的方法

我试过这个:

x = [30,31,32,33,34,35,36]
y = [1000, 2000, 3000, 4000, 3000, 2000, 1000]
##
sns.distplot(x, hist=True, kde=True,
    bins=int(150/150), color='darkblue',
    hist_kws={'edgecolor':'black'},
    kde_kws={'linewidth': 4})
plt.show()

但是没有得到我想要的

我希望有如下内容(仅用于我的数据)

enter image description here

(我从:https://towardsdatascience.com/histograms-and-density-plots-in-python-f6bda88f5ac0获得此图像)


Tags: 数据truedfdatamatplotlibseabornhist频率
1条回答
网友
1楼 · 发布于 2024-04-27 10:02:10

首先,请注意distplot已在Seaborn 0.11中折旧。扩展版和改进版现在被称为histplot(带有可选kde的直方图)、kdeplot(仅用于kde)和displot(创建子图)

可选的weights=参数为每个x值设置权重discrete=True需要为每个x值设置一个条。kde的cut参数控制曲线在数据点外绘制的距离

import matplotlib.pyplot as plt
import seaborn as sns

x = [30, 31, 32, 33, 34, 35, 36]
y = [1000, 2000, 3000, 4000, 3000, 2000, 1000]

sns.histplot(x=x, weights=y, discrete=True,
             color='darkblue', edgecolor='black',
             kde=True, kde_kws={'cut': 2}, line_kws={'linewidth': 4})
plt.show()

histplot with weights

请注意,如果基础数据是连续的,则通过提供原始数据,可以得到更精确的图

要更改kde行的颜色,一个明显的想法是使用line_kws={'color': 'red'},但这在当前的seaborn版本(0.11.1)中不起作用

但是,可以分别绘制histplotkdeplot。为了有匹配的y轴,histplot需要stat='density'(默认为'count'

ax = sns.histplot(x=x, weights=y, discrete=True, alpha=0.5,
                  color='darkblue', edgecolor='black', stat='density')
sns.kdeplot(x=x, weights=y, color='crimson', cut=2, linewidth=4, ax=ax)

另一种方法是在之后更改线条的颜色,它独立于所选的stat=工作

ax = sns.histplot(x=x, weights=y, discrete=True,
             color='darkblue', edgecolor='black',
             kde=True, kde_kws={'cut': 2}, line_kws={'linewidth': 4})
ax.lines[0].set_color('crimson')

sns.histplot with changed line color

以下是一个示例,说明如何将一个数据集的直方图与另一个数据集的kde曲线相结合:

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import seaborn as sns

x = [30, 31, 32, 33, 34, 35, 36]
y = [1000, 2000, 3000, 4000, 3000, 2000, 1000]
x2 = [20, 21, 22, 23, 24, 25, 26]
y2 = [1000, 2000, 3000, 4000, 3000, 2000, 1000]

ax = sns.histplot(x=x2, weights=y2, discrete=True, alpha=0.5,
                  color='darkblue', edgecolor='black', stat='density')
sns.kdeplot(x=x, weights=y, color='crimson', cut=2, linewidth=4, ax=ax)
ax.xaxis.set_major_locator(MultipleLocator(1))
plt.show()

combining a histplot with a kdeplot of a different dataset

相关问题 更多 >