我正在做一些聚类,结果是一个字符串列表,如下所示:
['5-3-2', '5-3-2', '4-3-2-1', ...]
我想根据字符串的频率绘制一个条形图。有什么简单的方法可以做到这一点吗?我想我可以识别列表中的独特元素并计算它们,但也许有一个更舒适的解决方案?
编辑:更多信息
import matplotlib.pyplot as plt
import numpy as np
import math as math
import Utils as ut
from sklearn.cluster import KMeans
from itertools import cycle
...
result = np.array(result)
keys, counts = np.unique(result, return_counts=True)
print('Keys: ', keys)
print('Counts: ', counts)
print(result)
plt.bar(keys,counts)
plt.show
输出:
Keys: ['3-1-4-2' '3-2-3-2' '3-3-2-2' '4-2-2-2' '4-2-3-1' '4-4-2']
Counts: [ 21 154 23 1 48 4]
编辑2:绘图在调试模式下显示,断点在plt.show
上,当我跨过它时它消失了。所以它在运行模式下是不可见的。有什么建议吗?
发布于 2018-02-28 05:54:24
np.unique
可以返回列表中唯一元素的计数。
keys, counts = np.unique(x, return_counts=True)
然后,您可以将它们绘制为条形图。
import matplotlib.pyplot as plt
import numpy as np
x = ['5-3-2', '5-3-2', '4-3-2', "2-3-2", '4-3-2', '4-3-2', "1-2-4"]
keys, counts = np.unique(x, return_counts=True)
plt.bar(keys, counts)
plt.show()
发布于 2018-02-28 04:04:22
频率的条形图本质上是直方图。幸运的是,matplotlib.pyplot
内置了直方图方法!
假设您的列表名为x
,您可以这样做:
import matplotlib.pyplot as plt
# the bins argument says how many bars (set to the number of unique values in your list)
# the rwidth argument is there so that the bars are not squished together
plt.hist(x, bins=len(set(x)), rwidth = 0.8)
plt.show()
这将为您提供列表中项目频率的直方图
https://stackoverflow.com/questions/49017002
复制相似问题