用lis制作python直方图

2024-04-18 11:23:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一些帮助用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文件包含以下内容:

^{pr2}$

我的路径显示:

12
6
4
4
6
6
4
4
8
4
4

还有更多的数字。在


Tags: csvpath代码inimport路径fortsv
1条回答
网友
1楼 · 发布于 2024-04-18 11:23:40

希望这就是你想要的?在

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()

将其作为输出: enter image description here

要添加轴名称,可以添加以下代码:

^{pr2}$

根据上传的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()

给出输出: enter image description here

相关问题 更多 >