完成 q4_2 散点图

This commit is contained in:
2509165005
2026-07-06 14:12:49 +08:00
parent d40ce14819
commit d107481792
3 changed files with 138 additions and 0 deletions

33
q4/q4_2/q4_2.py Normal file
View File

@@ -0,0 +1,33 @@
# q4_2.py
import json
import matplotlib.pyplot as plt
# 1. 读取文件
with open("movies.json", "r", encoding="utf-8") as f:
data = json.load(f)
# 2. 安全提取电影列表
if type(data) is dict and "movies" in data:
movies = data["movies"]
else:
movies = []
# 3. 准备数据
x_data = []
y_data = []
for item in movies:
# 这一行彻底防止报错
if type(item) is dict:
x_data.append(item["duration"])
y_data.append(item["rating"])
# 4. 画图(题目全部要求)
plt.scatter(x_data, y_data, color="red", alpha=0.6)
plt.title("时长与评分关系散点图")
plt.xlabel("时长(分钟)")
plt.ylabel("评分")
plt.savefig("q4_2_scatter.png", dpi=150)
plt.close()
print("运行成功!")