2024-09-19 23:41:18 发布
网友
我有一张频率表
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
知道我做错了什么吗?请帮忙
两件事:
当您向sns.displot提供数据帧时,还需要指定分发使用的列作为xkwarg
sns.displot
x
这就引出了第二个问题:我不知道使用sns.displot获得多个发行版的方法,但您可以大致这样使用sns.histplot:
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()
结果如下,请注意,我刚刚使用了一个示例数据集,以尽快获得一个粗略的图像:
首先,请注意,仅从频率创建kde绘图时,会丢失重要信息
sns.histplot()有一个参数weights=可以处理频率。我没有看到使用长数据帧和hue来实现这一点的方法,但是您可以为每个列分别调用histplot。以下是从生成的数据开始的示例:
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()
由于箱子宽度变化很大,因此没有足够的信息来绘制合适的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()
^{}有一些选项,例如dodge=False, alpha=0.5在同一点绘制条形图
dodge=False, alpha=0.5
两件事:
当您向
sns.displot
提供数据帧时,还需要指定分发使用的列作为x
kwarg这就引出了第二个问题:我不知道使用
sns.displot
获得多个发行版的方法,但您可以大致这样使用sns.histplot
:结果如下,请注意,我刚刚使用了一个示例数据集,以尽快获得一个粗略的图像:
首先,请注意,仅从频率创建kde绘图时,会丢失重要信息
sns.histplot()
有一个参数weights=
可以处理频率。我没有看到使用长数据帧和hue
来实现这一点的方法,但是您可以为每个列分别调用histplot
。以下是从生成的数据开始的示例:由于箱子宽度变化很大,因此没有足够的信息来绘制合适的kde曲线。此外,条形图似乎比直方图更合适。以下是一个示例:
^{} 有一些选项,例如
dodge=False, alpha=0.5
在同一点绘制条形图相关问题 更多 >
编程相关推荐