假设我们有一个名为'data.txt'的文本文件,内容如下:

apple,fruit,red
banana,fruit,yellow
carrot,vegetable,orange
tomato,fruit,red
potato,vegetable,brown

我们需要统计第二列不同值的数量,并用饼状图可视化。

代码如下:

import matplotlib.pyplot as plt

# 读取文件,获取第二列数据
with open('data.txt', 'r') as f:
    lines = f.readlines()

data = [line.split(',')[1].strip() for line in lines]

# 统计不同值的数量
count = {}
for d in data:
    if d not in count:
        count[d] = 1
    else:
        count[d] += 1

# 绘制饼状图
labels = list(count.keys())
sizes = list(count.values())

fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
ax.axis('equal')

# 保存图像
plt.savefig('pie_chart.png')

运行以上代码后,会生成一个名为'pie_chart.png'的饼状图,如下所示:

饼状图

其中,红色部分表示'fruit'出现的比例,黄色部分表示'vegetable'出现的比例。

Python统计文本文件第二列不同值数量并生成饼状图可视化

原文地址: https://www.cveoy.top/t/topic/jKto 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录