python - 每个百分位数的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()
解决方案
您可以使用以下方法简化所有这些:
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 来测试。):
推荐阅读
- java - Wiremock 捕获响应主体以供以后重用
- reactjs - Generic 应该是 BaseInputProps 吗?
- ios - React Native Button 绝对位置在真正的 iOS 特定设备上不起作用
- oracle - LPAD 函数没有从开始插入零
- r - 根据另一个日期值创建数据框
- java - Map XML attribute to specified tag(field) in Jackson Xml Mapper
- amazon-web-services - 如何使用 terraform 扩展 EC2 实例而不删除
- sql - Getting an error when using CONCAT in BigQuery
- angular - 如何从 entryComponent 获取数据到调用 entryComponent 的组件。
- php - 在 PHP 中为列表构建过滤器表单