用Python和列表绘制直方图

1 投票
1 回答
3312 浏览
提问于 2025-04-18 01:28

我需要一些帮助来在Python中制作一个直方图。

我有一些这样的代码:

import csv
import matplotlib.pyplot as plt

path = []

with open('paths_finished.tsv','r') as tsv:
    paths = [line.strip().split('\n') for line in tsv]
    newPath = paths[16:]
    counter = 0


for k in range(0,len(newPath)):
    path = newPath[counter][0].count(';')
    counter +=1

    print path

如果我打印路径,我会得到一个像(9, 5, 1, 3, 12, 7, 5, 9)这样的数字列表,依此类推。

现在我需要根据这个路径制作一个直方图。有人能帮我吗?

更新:

我的tsv文件包含这些内容:

['36dabfa133b20e3c', '1249525912', '112', '14th_century;China;Gunpowder;Fire', '2']
['20418ff4797f96be', '1229188046', '139', '14th_century;Time;Isaac_Newton;Light;Color;Rainbow', '1']
['08888b1b428dd90e', '1232241510', '74', '14th_century;Time;Light;Rainbow', '3']
['08888b1b428dd90e', '1232241601', '167', '14th_century;15th_century;Plato;Nature;Ultraviolet;Color;Rainbow', 'NULL']
['4cb0068c36658716', '1248654953', '253',  '14th_century;Time;Science;Nature;Weather;Sunlight;     <;Sun;Earth%27s_atmosphere;Ultraviolet;Color;Light;Rainbow', '3']
['1082b6b8501a04b1', '1248791776', '218', '14th_century;Christianity;Bible;God;Nature;Earth%27s_atmosphere;Ultraviolet;Optical_fiber;L    ight;Rainbow', '3']
['390ae528683f78ab', '1250727252', '66', '14th_century;Time;Astronomy;Light;Rainbow',   'NULL']
['0d57c8c57d75e2f5', '1283956474', '391', 

我的路径打印的是:

12
6
4
4
6
6
4
4
8
4
4

还有很多其他数字。

1 个回答

4

希望这正是你想要的内容?

path2 = list(set(path)) ## gets the unique values in the list

histo = []

for i in path2:
    histo.append(path.count(i)) ## add the number of occurances to the histo list

plt.bar(path2, histo)
plt.show()

这样会得到以下输出:

这里输入图片描述

如果你想给坐标轴添加名称,可以加上这段代码:

plt.suptitle('Title', fontsize=14)
plt.xlabel('Number', fontsize=12)
plt.ylabel('Freq', fontsize=12)

编辑 根据上传的tsv文件:

import csv
import matplotlib.pyplot as plt

path = []

with open('paths_finished.tsv','r') as tsv:
    paths = [line.strip().split('\n') for line in tsv]
    newPath = paths[16:]
    counter = 0

items = []
for k in range(0,len(newPath)):
    path = newPath[counter][0].count(';')
    counter +=1
    items.append(path)
    print path

print items


path2 = list(set(items)) ## gets the unique values in the list

histo = []

for i in path2:
    histo.append(items.count(i)) ## add the number of occurances to the histo list

plt.bar(path2, histo)
plt.suptitle('Title', fontsize=14)
plt.xlabel('Number', fontsize=12)
plt.ylabel('Freq', fontsize=12)
plt.show()

这样会得到的输出是:

这里输入图片描述

撰写回答