如何使用matplotlib从csv创建饼图

j2datikz  于 2023-03-05  发布在  其他
关注(0)|答案(2)|浏览(180)

尝试按照教程和答案在这里,但无法包裹我的头周围创建一个饼图的基础上,我的数据从一个csv。样本我的csv如下

post_id post_title  subreddit   polarity    subjectivity sentiment
0   bo7h4z  ['league']  soccer       -0.2             0.4    negative
1   bnvieg  ['césar']   soccer         0               0     neutral
2   bnup5q  ['foul']    soccer        0.1             0.6    positive
3   bnul4u  ['benfica'] soccer        0.45            0.5    positive
4   bnthuf  ['prediction']  soccer     0               0     neutral
5   bnolhc  ['revolution' ] soccer     0               0     neutral

还有更多的行,但我需要绘制情绪列,基本上有多少行是积极的,中性或消极的

outfile = open("clean_soccer.csv","r", encoding='utf-8')
file=csv.reader(outfile)
next(file, None)

post_id = []
post_title = []
subreddit = []
polarity =[]
subjectivity = []
sentiment = []

for row in file:
    post_id.append(row[0])
    post_title.append(row[1])
    subreddit.append(row[2])
    polarity.append(row[3])
    subjectivity.append(row[4])
    sentiment.append(row[5])

plt.pie( , labels=)
plt.axis('equal') 
plt.show()

会不会是和这个类似的东西?

tvz2xvvm

tvz2xvvm1#

我将提供一个简短的答案,只阅读sentiment列。您需要split来使用索引[5]访问情绪列。然后,您可以使用Counter来计算频率,然后使用这些值在饼图中绘制百分比。

import csv
from collections import Counter

outfile = open("clean_soccer.csv","r", encoding='utf-8')
file=csv.reader(outfile)
next(file, None)

sentiment = []

for row in file:
    sentiment.append(row[0].split()[5])

counts = Counter(sentiment[:-1])
plt.pie(counts.values(), labels=counts.keys(), autopct='%1.1f%%',)
plt.axis('equal')
plt.show()

编辑:在下面的评论中回答你的第二个问题

df['sentiment'].value_counts().plot.pie(autopct='%1.1f%%',)
plt.axis('equal')
plt.show()
eulz3vhy

eulz3vhy2#

import pandas as pd
import matplotlib.pyplot as plt
import csv

df = pd.read_csv('clean_soccer.csv')
df['sentiment'].value_counts().plot.pie()

plt.show()

此答案作为CC BY-SA 4.0下的OP plshelpme_如何使用matplotlib从csv创建饼图的问题的edit发布。

相关问题