如何从频率表中绘制直方图和分布?

2024-09-19 23:41:18 发布

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

我有一张频率表

frequency table

我一直想把这些数据画成这样

histogram with distribution curve

所以试过这个,

to_plot = compare_df[['counts', 'theoritical counts']]
bins=[0,2500,5000,7500,10000,12500,15000,17500,20000]
sns.displot(to_plot,bins=bins)

但是结果是这样的,, plot

知道我做错了什么吗?请帮忙


Tags: to数据dfplotwithtabledistribution频率
2条回答

两件事:

  1. 当您向sns.displot提供数据帧时,还需要指定分发使用的列作为xkwarg

  2. 这就引出了第二个问题:我不知道使用sns.displot获得多个发行版的方法,但您可以大致这样使用sns.histplot

import matplotlib.pyplot as plt
import seaborn as sns 

titanic = sns.load_dataset('titanic')

ax = sns.histplot(data=titanic,x='age',bins=30,color='r',alpha=.25,
                  label='age')
sns.histplot(data=titanic,x='fare',ax=ax,bins=30,color='b',alpha=.25,
             label='fare')         
ax.legend()
plt.show()

结果如下,请注意,我刚刚使用了一个示例数据集,以尽快获得一个粗略的图像:

enter image description here

首先,请注意,仅从频率创建kde绘图时,会丢失重要信息

sns.histplot()有一个参数weights=可以处理频率。我没有看到使用长数据帧和hue来实现这一点的方法,但是您可以为每个列分别调用histplot。以下是从生成的数据开始的示例:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

sns.set()
bins = np.array([0, 2500, 5000, 7500, 10000, 12500, 15000, 17500, 20000])
df = pd.DataFrame({'counts': np.random.randint(2, 30, 8),
                   'theoretical counts': np.random.randint(2, 30, 8)},
                  index=pd.interval_range(0, 20000, freq=2500))
df['theoretical counts'] = (3 * df['counts'] + df['theoretical counts']) // 4
fig, ax = plt.subplots()
for column, color in zip(['counts', 'theoretical counts'], ['cornflowerblue', 'crimson']):
    sns.histplot(x=(bins[:-1] + bins[1:]) / 2, weights=df[column], bins=8, binrange=(0, 20000),
                 kde=True, kde_kws={'cut': .3},
                 color=color, alpha=0.5, label=column, ax=ax)
ax.legend()
ax.set_xticks(range(0, 20001, 2500))
plt.show()

sns.histplot from frequencies

由于箱子宽度变化很大,因此没有足够的信息来绘制合适的kde曲线。此外,条形图似乎比直方图更合适。以下是一个示例:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

sns.set()
bins = [0, 250, 500, 1000, 1500, 2500, 5000, 10000, 50000, np.inf]
bin_labels = [f'{b0}-{b1}' for b0, b1, in zip(bins[:-1], bins[1:])]
df = pd.DataFrame({'counts': np.random.randint(2, 30, 9),
                   'theoretical counts': np.random.randint(2, 30, 9)})
df['theoretical counts'] = (3 * df['counts'] + df['theoretical counts']) // 4
fig, ax = plt.subplots(figsize=(10, 4))
sns.barplot(data=df.melt(), x=np.tile(bin_labels, 2), y='value',
            hue='variable', palette=['cornflowerblue', 'crimson'], ax=ax)
plt.tight_layout()
plt.show()

bar plots

^{}有一些选项,例如dodge=False, alpha=0.5在同一点绘制条形图

相关问题 更多 >