假设我有一个30列的数据框架,前10列是各种收集数据的"平均值",接下来10列是"中间值",最后10列是"模式".例如,第1列是height_mean,第10列是height_median,第20列是height_mode.第2列是weight_mean,第11列是weight_median,第21列是weight_median.

height_mean ... height_median ... height_mode ...
56 ... 58 ... 55 ...

我想创建一个10x3的子图,它取每个变量的平均值、中值和模式图,并相邻地绘制它们,这样子图的每一行都是一个新变量.因此,第一行子地块将有高度的平均值、中位数和模式图,第二行子地块将有重量的平均值、中位数和模式图,依此类推.

到目前为止,我已经有了这个,它按照列在数据帧中的顺序创建子图:

fig, axs = plt.subplots(10, 3, figsize=(20,20))

for count, ax in zip(df.columns, axs.ravel()):
    df_data.loc[:,[count]].boxplot(ax=ax)
plt.show()  

我try 过这样做,但没有成功:

for n, column in enumerate(df_columns):
    # add a new subplot iteratively
    ax = plt.subplot(10, 3, n + 1)
    df_data.iloc[:,[n]].boxplot(ax=ax)
    ax = plt.subplot(10, 3, n + 2)
    df_data.iloc[:,[n+9]].boxplot(ax=ax)
    ax=plt.subplot(10,3,n+3)
    df_data.iloc[:,[n+19]].boxplot(ax=ax)

推荐答案

要按列迭代子批次,最简单的方法是在散列之前转置axs,即axs.T.ravel():

for col, ax in zip(df.columns, axs.T.ravel()):

最简单的例子:

headers = ['height_mean', 'weight_mean', 'height_median', 'weight_median', 'height_mode', 'weight_mode']
df = pd.DataFrame(np.random.random((10, 6)), columns=headers)
#    height_mean  weight_mean  height_median  weight_median  height_mode  weight_mode
# 0     0.982351     0.548713       0.559040       0.497497     0.842977     0.738946
# 1     0.832716     0.660227       0.754149       0.286536     0.315156     0.312089
# 2     0.997460     0.290112       0.501917       0.974751     0.097419     0.559542

ncols = 3
nrows = len(df.columns) // ncols

fig, axs = plt.subplots(nrows, ncols, sharey=True, constrained_layout=True)
for col, ax in zip(df.columns, axs.T.ravel()):
    df[[col]].boxplot(ax=ax)

Python相关问答推荐

将每个关键字值对转换为pyspark中的Intramame列

Asyncio与队列的多处理通信-仅运行一个协程

Plotly Dash函数来切换图形参数-pPython

为什么我的主页不会重定向到详细视图(Django)

code _tkinter. Tcl错误:窗口路径名称错误.!按钮4"

如何将桌子刮成带有Se的筷子/要求/Beautiful Soup ?

使文本输入中的文本与标签中的文本相同

将HLS纳入媒体包

从收件箱中的列中删除html格式

Python 约束无法解决n皇后之谜

使用miniconda创建环境的问题

_repr_html_实现自定义__getattr_时未显示

在极性中创建条件累积和

递归访问嵌套字典中的元素值

未知依赖项pin—1阻止conda安装""

在单个对象中解析多个Python数据帧

让函数调用方程

如何更改groupby作用域以找到满足掩码条件的第一个值?

Maya Python脚本将纹理应用于所有对象,而不是选定对象

在不同的帧B中判断帧A中的子字符串,每个帧的大小不同