如何在Python中循环创建多个图?
我有一个表格,里面有主题、分数1、分数2、分数3和分数4这几列。
| id | score1 | score2 | score3 | score4 |
|----|--------|---------|----------|---------|
| 1 | 0.05 | 0.0608 | 0.476464 | 0.53535 |
| 1 | 0.08 | 0.0333 | 0.8263 | 0.9463 |
| 1 | 0.05 | 0.0926 | 0.8694 | 0.9903 |
| 2 | 0.08 | 0.0425 | 0.1948 | 0.3958 |
| 2 | 0.09 | 0.0992 | 0.1238 | 0.1937 |
| 4 | 0.1 | 0.0627 | 0.0738 | 0.0987 |
| 4 | 0.05 | 0.06262 | 0.721 | 0.12 |
| 4 | 0.04 | 0.05227 | 0.0825 | 0.283 |
| 4 | 0.02 | 0.04728 | 0.0628 | 0.0936 |
我想为每个ID创建一个图表。这个图表应该显示四个分数中每个ID的数量。我想为每个ID制作多个图表(这里是为ID 1、2和4分别制作图表)。
这是我到目前为止尝试的内容。
我使用SQL创建了一个单独的列来分类每个分数,然后用下面的Python代码来绘图。但我只生成了一个图表。
plt.figure(figsize=(10, 6))
sns.countplot(x='score', data=df1)
plt.xlabel('Score')
plt.xticks(rotation=90)
plt.ylabel('Count')
plt.title('Distribution per score - id 1')
plt.show()
有没有更简单的方法,可以只用Python完成这些操作,并绘制多个图表呢?
1 个回答
0
这可以通过使用循环和直方图来实现,下面是用matplotlib绘制的示例:
import matplotlib.pyplot as plt
ids=[1,1,1,2,2,4,4,4,4]
score1=[0.05,0.08,0.05,0.08,0.09,0.1,0.05,0.04,0.02]
score2=[0.0608,0.0333,0.0926,0.0425,0.0992,0.0627,0.06262,0.05227,0.04728]
score3=[0.476464,0.8263,0.8694,0.1948,0.1238,0.0738,0.721,0.0825,0.0628]
score4=[0.53535,0.9463,0.9903,0.3958,0.1937,0.0987,0.12,0.283,0.0936]
scoredf=pd.DataFrame({'id':ids,'score1':score1,'score2':score2,'score3':score3,'score4':score4})
uniqueids=scoredf['id'].unique()
for i in uniqueids:
tempdf=scoredf[scoredf['id']==i]
tempdf=tempdf.drop(['id'], axis=1)
plt.hist(tempdf,bins=3)
plt.xlabel('Score')
plt.xticks(rotation=90)
plt.ylabel('Count')
plt.title('Distribution per score - id '+str(i))
plt.show()