我看到另一個問題,我可以使用Counter()
來計算一組字符串中出現的次數。所以如果我有['A','B','A','C','A','A']
我得到Counter({'A':3,'B':1,'C':1})
。但是現在,我如何使用這些信息來構建一個直方圖?在Python中使用Counter()來創建直方圖?
25
A
回答
42
對於您的數據,最好使用條形圖而不是直方圖。看看這個代碼:
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
labels, values = zip(*Counter(['A','B','A','C','A','A']).items())
indexes = np.arange(len(labels))
width = 1
plt.bar(indexes, values, width)
plt.xticks(indexes + width * 0.5, labels)
plt.show()
結果:
9
你可以寫一些非常簡潔的代碼來做到這一點使用pandas:
In [24]: import numpy as np
In [25]: from pandas import Series
In [27]: sample = np.random.choice(['a', 'b'], size=10)
In [28]: s = Series(sample)
In [29]: s
Out[29]:
0 a
1 b
2 b
3 b
4 a
5 b
6 b
7 b
8 b
9 a
dtype: object
In [30]: vc = s.value_counts()
In [31]: vc
Out[31]:
b 7
a 3
dtype: int64
In [32]: vc = vc.sort_index()
In [33]: vc
Out[33]:
a 3
b 7
dtype: int64
In [34]: vc.plot(kind='bar')
,導致:
相關問題
- 1. Python - 創建直方圖
- 2. 的Python/Pyside:創建圖像直方圖
- 3. 在Python中手動高效地創建圖像直方圖
- 4. Python:創建文件來存儲直方圖?
- 5. 在Ruby中創建直方圖
- 6. 在ggplot2中創建密度直方圖?
- 7. 如何在Java中創建直方圖
- 8. Python Counter Counter and subtract
- 9. 如何在python中創建對數日誌直方圖
- 10. 試圖用ZedGraph創建直方圖
- 11. 在xy風格創建直方圖數據的loglog圖-python,matplotlib,
- 12. 在psql中創建「counter」數組
- 13. 如何創建直方圖
- 14. 創建直方圖OCaml
- 15. 使用Counter-Python查找GCD
- 16. 使用3通道使用opencv創建直方圖圖表
- 17. 在Python中使用Pylab創建圖形
- 18. 從3個不同的直方圖創建圖像直方圖
- 19. 用熊貓數據框創建堆疊直方圖數據python
- 20. 如何從python中的hashmap創建直方圖?
- 21. 任何方式來在C#中的OutOfMemoryException上創建堆轉儲/直方圖?
- 22. 使用sqlite中的動態分區數創建直方圖
- 23. EmguCV:創建圖像直方圖 - 錯誤
- 24. C++試圖創建直方圖
- 25. 如何創建直方圖的直方圖?
- 26. 使用張量流創建圖像的顏色直方圖
- 27. 使用RGB圖像創建HSV直方圖
- 28. 使用python創建圖表
- 29. 如何在opencv中創建可用於calcBackProject的直方圖?
- 30. 從子集函數創建的子集中創建直方圖
如果你想建立一個直方圖我建議你使用numpy和matplotlib – jabaldonedo
在技術上看一下[matplotlib](http://matplotlib.org/) –
,*是一個直方圖 - 它有組件(字母)和頻率(它們發生的次數)。你在問怎麼把它變成條形圖嗎? –