|
|
|
@ -0,0 +1,73 @@
|
|
|
|
|
import os
|
|
|
|
|
from pyecharts import options as opts
|
|
|
|
|
from pyecharts.charts import Bar
|
|
|
|
|
|
|
|
|
|
def generate_bar_chart_from_result(result, x_column: str, y_column: str, output_file: str = "bar_chart.html"):
|
|
|
|
|
"""
|
|
|
|
|
根据结果集生成柱状图并保存为 HTML 文件。
|
|
|
|
|
|
|
|
|
|
参数:
|
|
|
|
|
result: 结果集,通常是一个列表(字典格式)。
|
|
|
|
|
x_column (str): 作为 X 轴的列名。
|
|
|
|
|
y_column (str): 作为 Y 轴的列名。
|
|
|
|
|
output_file (str): 输出 HTML 文件名(默认 "bar_chart.html")。
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
# 如果结果集为空,直接返回
|
|
|
|
|
if not result:
|
|
|
|
|
raise ValueError("结果集为空,无法生成图表!")
|
|
|
|
|
|
|
|
|
|
# 检查列名是否存在
|
|
|
|
|
if x_column not in result[0]:
|
|
|
|
|
raise ValueError(f"X 轴列名 '{x_column}' 不存在!")
|
|
|
|
|
if y_column not in result[0]:
|
|
|
|
|
raise ValueError(f"Y 轴列名 '{y_column}' 不存在!")
|
|
|
|
|
|
|
|
|
|
# 提取 X 轴和 Y 轴数据
|
|
|
|
|
x_axis_data = [f"{row['学段']} - {row['科目']}" for row in result] # 组合学段和科目作为 X 轴
|
|
|
|
|
y_axis_data = [row[y_column] for row in result]
|
|
|
|
|
|
|
|
|
|
print("X 轴数据:", x_axis_data)
|
|
|
|
|
print("Y 轴数据:", y_axis_data)
|
|
|
|
|
|
|
|
|
|
# 创建柱状图
|
|
|
|
|
bar = Bar()
|
|
|
|
|
bar.add_xaxis(x_axis_data)
|
|
|
|
|
bar.add_yaxis("课程数量", y_axis_data)
|
|
|
|
|
|
|
|
|
|
# 设置全局配置
|
|
|
|
|
bar.set_global_opts(
|
|
|
|
|
title_opts=opts.TitleOpts(title="学段-科目课程数量柱状图"),
|
|
|
|
|
xaxis_opts=opts.AxisOpts(name="学段-科目", axislabel_opts=opts.LabelOpts(rotate=45)), # X 轴标签旋转 45 度
|
|
|
|
|
yaxis_opts=opts.AxisOpts(name="课程数量"),
|
|
|
|
|
legend_opts=opts.LegendOpts(is_show=True)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# 保存为 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}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 示例数据
|
|
|
|
|
result = [
|
|
|
|
|
{"学段": "小学", "科目": "语文", "课程数量": 120},
|
|
|
|
|
{"学段": "小学", "科目": "数学", "课程数量": 100},
|
|
|
|
|
{"学段": "初中", "科目": "语文", "课程数量": 150},
|
|
|
|
|
{"学段": "初中", "科目": "数学", "课程数量": 130},
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
# 生成柱状图
|
|
|
|
|
generate_bar_chart_from_result(
|
|
|
|
|
result,
|
|
|
|
|
x_column="学段",
|
|
|
|
|
y_column="课程数量",
|
|
|
|
|
output_file="d:/lesson_bar_chart.html"
|
|
|
|
|
)
|