python - 在箱形图中绘制数据框的值
问题描述
我有一个单列数据框,如下所示
df = pd.DataFrame(np.random.randn(20, 1),
columns=['Time'])
df['EDGE'] = pd.Series(['A', 'A', 'A','B', 'B', 'A', 'B','C','C', 'B','D','A','E','F','F','A','G','H','H','A'])
df
真实的数据框有几十万行,唯一的“EDGE”值列表约为 200
我想以箱线图方式绘制结果,如下所示:
boxplot = df.boxplot(by='EDGE')
现在有这么多的值,我必须打印一点,只需在同一个图中先说 10 个首字母。另一方面,我想首先打印平均时间较长的值。
预期结果:每个箱线图都有一系列箱线图,包括 10 个边。关于平均“时间”按降序显示的框。
如何进行?
我尝试了什么?
我尝试使用 loc 为每个值制作 sub_df ,但随后每个箱线图只能得到一个框 我尝试使用 groupby 通过“EDGE”进行浏览无济于事,因为我不知道如何仅绘制前 n 组数据框
注意:我假装使用尽可能少的库,即如果我可以使用 pandas 比使用 matplotlib 更好,并且 matplotlib 比使用 matplotlib 之上的另一个库更好
解决方案
IIUC,那么您可以通过重塑数据框来做到这一点
# define the number of edges per plot
nb_edges_per_plot = 4 #to change to your needs
# group by edge
gr = df.groupby('EDGE')['Time']
# get the mean per group and sort them
order_ = gr.mean().sort_values(ascending=False).index
print (order_) #order depends on the random value so probably not same for you
#Index(['D', 'H', 'C', 'B', 'A', 'E', 'G', 'F'], dtype='object', name='EDGE')
# reshape your dataframe to ake each EDGE a column and order the columns
df_ = df.set_index(['EDGE', gr.cumcount()])['Time'].unstack(0)[order_]
print (df_.iloc[:5, :5])
# EDGE D H C B A
# 0 1.729417 0.270593 -0.140786 -0.540270 0.862832
# 1 NaN 0.647830 1.038952 -0.129361 -0.648432
# 2 NaN NaN NaN -1.235637 -0.430890
# 3 NaN NaN NaN 0.631744 -1.622461
# 4 NaN NaN NaN NaN 0.694052
现在你可以只boxplot
用groupby
. 要在子图上绘制每组边,请执行以下操作:
df_.groupby(np.arange(len(order_))//nb_edges_per_plot, axis=1).boxplot()
或者如果你想要分开的数字,那么你可以做
for _, dfg_ in df_.groupby(np.arange(len(order_))//nb_edges_per_plot, axis=1):
dfg_.plot(kind='box')
甚至在一行中您也可以得到单独的数字,看看区别是不是使用boxplot()
use plot.box()
。请注意,如果您想更改每个绘图中的参数,则循环版本更加灵活
df_.groupby(np.arange(len(order_))//nb_edges_per_plot, axis=1).plot.box()
推荐阅读
- html - 应用后无法保持表格的格式
- css - “display:none”是否会阻止内容被加载?
- c - 如何计算字符串中的字符数(如果没有占用所有空间)
- logging - 用于高效日志文件压缩的库
- watchkit - 在 watchOS 的后台发出网络请求
- gtk3 - Yocto 配置:错误:未满足软件包要求(gtk+-3.0 >= 3.14.0)
- oracle - 如何将 PL/SQL 脚本的结果输出到网格?
- javascript - 返回 JSON 格式的 HTML 并调用函数
- php - MySQL: Acquiring data from related tables
- regex - 正则表达式解析问题