首页 > 解决方案 > 每个百分位数的python绘图线

问题描述

如何绘制pandas.DataFrame.describe使用 seaborn 为每个百分位数计算的百分位数?

目前,我需要遍历每一个。相反,我想要一个包含所有百分位数的图表。https://seaborn.pydata.org/generated/seaborn.lineplot.html 有一些很好的色调和风格示例,但我目前想知道如何正确重塑数据框以便能够使用这种方法。

import pandas as pd
%pylab inline

df = pd.DataFrame({'dt':['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-03'], 'bar':[1,2,3, 4], 'baz':[3,4,5, 6]})
df['dt'] = pd.to_datetime(df['dt'])
display(df)

df = df.groupby(['dt']).describe()
df = df.reset_index()
df = df.set_index(['dt'], drop=False)
display(df)

import seaborn as sns; sns.set()

# iterate for each column (bar, baz)
df_plot = df[['dt']].copy()

# iterate for each percentile
df_plot['metric'] = df['bar']['25%']
sns.lineplot(x='dt', y='metric', data=df_plot)
plt.show()

df_plot['metric'] = df['bar']['50%']
sns.lineplot(x='dt', y='metric', data=df_plot)
plt.show()

df_plot['metric'] = df['bar']['75%']
sns.lineplot(x='dt', y='metric', data=df_plot)
plt.show()

标签: pythonpandasseabornreshapepercentile

解决方案


您可以使用以下方法简化所有这些:

import pandas as pd
import seaborn as sns
%pylab inline

df = pd.DataFrame({'dt':['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-03'], 'bar':[1,2,3, 4], 'baz':[3,4,5, 6]})
df = df.groupby(['dt']).describe()
sns.lineplot(data=df['baz'][['25%', '50%', '75%']])

结果(也许有额外的plt.show()?我没有安装 pylab 来测试。):

在此处输入图像描述


推荐阅读