Python 使用 Pandas 和 Matplotlib 分析专家打分数据并生成直方图
import pandas as pd
import matplotlib.pyplot as plt
import random
# 读取CSV文件
df = pd.read_csv('专家打分.csv', encoding='gbk')
# 你的数据
clusters = {
'Cluster 0': [12, 15, 17, 24, 30, 35, 38, 40, 41, 43, 44, 47, 53, 54, 62, 63, 69, 70, 71, 72, 76, 78, 79, 80, 83, 84, 87, 89, 97],
'Cluster 1': [11, 13, 16, 18, 19, 22, 26, 34, 57, 61, 67, 73, 74, 85, 86, 91, 94, 96],
'Cluster 2': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 20, 21, 23, 25, 27, 28, 29, 31, 32, 33, 36, 37, 39, 42, 45, 46, 48, 49, 50, 51, 52, 55, 56, 58, 59, 60, 64, 65, 66, 68, 75, 77, 81, 82, 88, 90, 92, 93, 95]
}
# 对每个类别随机选择8个数,并进行统计
for cluster, data in clusters.items():
random_sample = random.sample(data, 2)
# 选择对应专家序号的行
selected_rows = df[df['专家序号'].isin(random_sample)]
selected_rows = df
# 对每个选中的专家,绘制其所有列的直方图
for i, row in selected_rows.iterrows():
fig, ax = plt.subplots()
row[1:].dropna().astype(float).hist(ax=ax) # 从第一列开始,去掉空值,转换为浮点数
ax.set_title(f'Expert {row['专家序号']} in {cluster}')
plt.xlabel('Score')
plt.ylabel('Frequency')
plt.savefig(f'Expert_{row['专家序号']}_in_{cluster}.png')
plt.close(fig)
在这个代码中,添加了plt.savefig()方法来保存图片,图片的文件名根据专家序号和类别进行命名。每次循环结束后,使用plt.close(fig)关闭当前图形,以便下一个循环开始时创建新的图形。
原文地址: https://www.cveoy.top/t/topic/bD2Z 著作权归作者所有。请勿转载和采集!