Files
2026-07-06 17:06:51 +08:00

41 lines
1.1 KiB
Python

# q4_1.py
import json
import matplotlib.pyplot as plt
# 1. 读取books.json文件
with open("books.json", "r", encoding="utf-8") as f:
data = json.load(f)
books = data["books"]
# 2. 统计各出版社图书数量
pub_count = {}
for book in books:
pub_name = book["publisher"]
if pub_name in pub_count:
pub_count[pub_name] += 1
else:
pub_count[pub_name] = 1
# 拆分x轴、y轴数据
publish_names = list(pub_count.keys())
book_nums = list(pub_count.values())
# 3. 配置画布与绘图
plt.figure(figsize=(10, 6))
# 生成不同颜色
colors = plt.cm.tab10(range(len(publishing_names)))
# 绘制柱状图
plt.bar(publishing_names, book_nums, color=colors)
# 4. 图表样式设置
plt.title("出版社图书数量分布", fontsize=14)
plt.xlabel("出版社名称", fontsize=12)
plt.ylabel("图书数量", fontsize=12)
# X轴文字旋转45度防止重叠
plt.xticks(rotation=45, ha="right")
# 自动调整布局,避免标签被截断
plt.tight_layout()
# 5. 保存图片
plt.savefig("q4_1_bar.png", dpi=150)
plt.show()