You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将参数列表传入category_mode并批量调用create_catplot?

批量处理多参数并生成可视化图表的实现方案

问题背景

现有两个Python函数category_mode和create_catplot,传入单个参数(如'RecipeName')时可正常运行,但需支持传入参数列表(例如li=['Format','RecipeName','MachineState','MachineMode']),实现批量处理每个参数并生成对应可视化图表。

解决方案

新增一个批量处理函数,遍历参数列表完成数据处理与绘图,同时补充图表显示、布局调整的逻辑(原绘图函数未包含相关步骤)。

完整代码

保留原有导入语句与函数,新增批量处理逻辑:

from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt  # 新增导入,用于图表显示与布局调整

def category_mode(df,x):
    newdf=df[df['Availability2']!='2']
    newdf=newdf.dropna(subset=[x])
    newdf=newdf[[x,'Availability2']]
    newdf=newdf.groupby([x, 'Availability2'])['Availability2'].count().unstack()
    newdf.loc['Total', :] = newdf.sum().values
    newdf['Total']=newdf.groupby(x).sum().sum(axis=1)
    newdf['Availability']=newdf['0']/newdf['Total']*100
    newdf=newdf.reset_index()
    return newdf

def create_catplot(newdf,val):
    x=newdf[val]
    y=newdf['Total']
    y1=newdf['Availability']
    g = sns.barplot(x=x, y=y, color='blue')
    g2 = sns.lineplot(x=range(len(x)), y=y1, color='orange', marker='o', ax=g.axes.twinx())
    g.set_xticklabels(g.get_xticklabels(), rotation=90)
    g.set_xlabel(val)
    g.set_ylabel('Total')
    g2.set_ylabel('Availability')
    g.legend(handles=[Rectangle((0,0), 0, 0, color='blue', label='Recipe Counts'), Line2D([], [], marker='o', color='orange', label='Availability')], loc=(1.1,0.8))
    plt.tight_layout()  # 调整布局,避免标签被截断

# 新增批量处理函数
def batch_process_and_plot(df, param_list):
    # 存储每个参数处理后的结果
    result_dict = {}
    for param in param_list:
        processed_df = category_mode(df, param)
        result_dict[param] = processed_df
        
    # 遍历结果生成图表
    for param, df_plot in result_dict.items():
        plt.figure(figsize=(10,6))  # 设置图表尺寸
        create_catplot(df_plot, param)
        plt.title(f'Analysis for {param}')  # 添加图表标题
        plt.show()  # 显示当前图表
        # 可选:保存图表到本地文件
        # plt.savefig(f'{param}_analysis.png', bbox_inches='tight')
        plt.close()  # 关闭当前图表,释放内存资源

使用示例

假设你的原始数据框为original_df,参数列表为目标字段集合,调用方式如下:

# 假设original_df是你的原始数据集
target_params = ['Format','RecipeName','MachineState','MachineMode']
batch_process_and_plot(original_df, target_params)

说明

  1. batch_process_and_plot函数先遍历参数列表,调用category_mode处理每个字段,将结果存入字典便于后续复用;
  2. 逐个取出处理后的DataFrame,调用create_catplot生成双轴图表,同时补充标题、布局调整、图表显示的逻辑;
  3. 若需要保存图表,可取消注释plt.savefig行,生成的图片会以字段名命名,保存在当前工作目录。

内容的提问来源于stack exchange,提问作者Jahrakal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 07:35:18