import os from pyecharts import options as opts from pyecharts.charts import Bar from pyecharts.commons.utils import JsCode def generate_bar_chart_from_result(result, x_columns: list, y_columns: list, output_file: str = "bar_chart.html"): """ 根据结果集生成柱状图并保存为 HTML 文件。 参数: result: 结果集,通常是一个列表(字典格式)。 x_columns (list): 作为 X 轴的列名列表。 y_columns (list): 作为 Y 轴的列名列表。 output_file (str): 输出 HTML 文件名(默认 "bar_chart.html")。 """ try: # 如果结果集为空,直接返回 if not result: raise ValueError("结果集为空,无法生成图表!") # 检查列名是否存在 for col in x_columns + y_columns: if col not in result[0]: raise ValueError(f"列名 '{col}' 不存在!") # 提取 X 轴数据(动态组合多列) x_axis_data = [" - ".join(str(row[col]) for col in x_columns) for row in result] # 提取 Y 轴数据 y_axis_data = [row[y_columns[0]] for row in result] # 目前只支持一个 Y 轴列 # 为每个柱状图设置不同颜色 colors = [ "#5470C6", "#91CC75", "#EE6666", "#73C0DE", "#3BA272", "#FC8452", "#9A60B4", "#EA7CCC" ] # 自定义颜色列表 # 创建柱状图并配置布局 bar = Bar() bar.add_xaxis(x_axis_data) bar.add_yaxis( series_name=y_columns, y_axis=y_axis_data, bar_width="30%", # 控制柱宽 itemstyle_opts=opts.ItemStyleOpts( color=JsCode(f''' function(params) {{ var colorList = {colors}; return colorList[params.dataIndex % colorList.length]; }} ''') ) ) bar.set_global_opts( xaxis_opts=opts.AxisOpts( name=" - ".join(x_columns), axislabel_opts=opts.LabelOpts(rotate=45), boundary_gap=True, # 开启分类间隙 splitline_opts=opts.SplitLineOpts(is_show=False) ), yaxis_opts=opts.AxisOpts(name=y_columns), legend_opts=opts.LegendOpts(is_show=True) ) # 确保目标目录存在 if not os.path.exists(os.path.dirname(output_file)): os.makedirs(os.path.dirname(output_file)) # 保存为 HTML 文件 bar.render(output_file) print(f"柱状图已保存为 {output_file}") # 检查文件是否存在 if os.path.exists(output_file): print("文件生成成功!") else: print("文件生成失败!") except Exception as e: print(f"生成柱状图时发生错误: {e}")