gpt4 book ai didi

python - 迭代 DataFrame 分类列以创建子图

转载 作者:太空宇宙 更新时间:2023-11-03 20:35:29 24 4
gpt4 key购买 nike

我正在尝试为预定的 x 和 y 数据创建子图网格。这些函数应该迭代 pandas DataFrame,识别分类变量,并针对给定分类变量的每个级别用一条线绘制 x 和 y 数据。图的数量等于分类变量的数量,每个图上的线数应反射(reflect)该变量的类别数量。

我最初尝试将 Dataframe 分组到给定分类变量的 For 循环中,但得到了一些好坏参半的结果。我认为我的问题在于如何分配绘制线条的轴。


def grouping_for_graphs(df,x_col, y_col,category,func):
'''
funtion to group dataframe given a variable and
aggregation function

'''
X = df[x_col].name
y = df[y_col].name
category = df[category].name

df_grouped = df.groupby([X, category])[y].apply(func)
return df_grouped.reset_index()


# create a list of categorical variables to plot
cat_list = []
col_list = list(df.select_dtypes(include = ['object']).columns)

for col in col_list:
if len(df[col].unique()) < 7:
cat_list.append(col)


# create plots and axes
fig, axs = plt.subplots(2, 2, figsize=(30,24))
axs = axs.flatten()
# pick plot function
plot_func = plt.plot

# plot this
for ax, category in zip(axs, cat_list):
df_grouped = grouping_for_graphs(df,x_col, y_col,category,agg_func)
x_col = df_grouped.columns[0]
y_col = df_grouped.columns[-1]
category = str(list(df_grouped.columns.drop([x_lab, y_lab]))[0])
for feature in list(df_grouped[category].unique()):
X = df_grouped[df_grouped[category] == feature][x_col]
y = df_grouped[df_grouped[category] == feature][y_col]
ax.plot = plot_func(X,y)
ax.set_xlabel(x_col)
ax.set_ylabel(y_col)
ax.set_title(feature)

除了收到 ax.plot 是“列表”对象且不可调用的错误之外,所有绘制的线条都放在子图的最终图上。

最佳答案

我对你的plot_func感到困惑。删除它并直接使用 ax.plot(X, y) 进行绘图。修改的行通过注释突出显示

fig, axs = plt.subplots(2, 2, figsize=(30,24))
axs = axs.flatten()

for ax, category in zip(axs, cat_list):
df_grouped = grouping_for_graphs(df,x_col, y_col,category,agg_func)
x_col = df_grouped.columns[0]
y_col = df_grouped.columns[-1]
category = str(list(df_grouped.columns.drop([x_lab, y_lab]))[0])
for feature in list(df_grouped[category].unique()):
X = df_grouped[df_grouped[category] == feature][x_col]
y = df_grouped[df_grouped[category] == feature][y_col]
ax.plot(X,y) # <--- Modified here
ax.set_xlabel(x_col)
ax.set_ylabel(y_col)
ax.set_title(feature)

关于python - 迭代 DataFrame 分类列以创建子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57191944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com