Files
simulated-examination/q4/q4_1/q4_1.py

45 lines
1.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import json
import matplotlib.pyplot as plt
from collections import Counter
# 设置中文字体(解决中文乱码问题,必加!)
plt.rcParams['font.sans-serif'] = ['SimHei'] # 黑体
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# 1. 读取movies.json数据
try:
with open('movies.json', 'r', encoding='utf-8') as f:
movies_data = json.load(f)
except FileNotFoundError:
print("错误未找到movies.json文件请确认文件在当前目录")
exit()
# 2. 统计各类型电影数量(处理多类型分隔,比如"剧情/喜剧"拆分为两个类型)
genre_list = []
for movie in movies_data:
# 假设movies.json里的类型字段是"genre",如果是其他名称(如"type")请修改
genres = movie.get('genre', '').split('/') # 按/拆分多类型
genre_list.extend([g.strip() for g in genres if g.strip()]) # 去空格并过滤空值
genre_counter = Counter(genre_list) # 统计各类型数量
# 3. 提取X轴类型和Y轴数量数据
x_labels = list(genre_counter.keys())
y_values = list(genre_counter.values())
# 4. 绘制柱状图
plt.figure(figsize=(10, 6)) # 设置画布大小
plt.bar(x_labels, y_values, color='skyblue') # 用plt.bar绘制柱状图
# 5. 设置标题和坐标轴(按要求配置)
plt.title("类型电影数量分布", fontsize=14) # 标题
plt.xlabel("电影类型", fontsize=12) # X轴标签可选更清晰
plt.ylabel("电影数量", fontsize=12) # Y轴标签可选更清晰
plt.xticks(rotation=45, ha='right') # X轴文字旋转避免重叠可选优化
plt.tight_layout() # 自动调整布局,防止文字被截断
# 6. 保存图片按要求q4_1_bar.pngdpi=150
plt.savefig('q4_1_bar.png', dpi=150)
plt.close() # 关闭画布,释放资源
print("柱状图绘制完成已保存为q4_1_bar.png")