如何从 Python 中的字符串列表制作直方图?
How to make a histogram from a list of strings in Python?
我有一个字符串列表:
a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
我想制作一个直方图来显示字母的频率分布。我可以使用以下代码制作一个包含每个字母计数的列表:
from itertools import groupby
b = [len(list(group)) for key, group in groupby(a)]
如何制作直方图?我可能在列表 a
.
中有一百万个这样的元素
查看 matplotlib.pyplot.bar
。还有 numpy.histogram
如果你想要更宽的垃圾箱,它会更灵活。
与其使用 groupby()
(这需要对输入进行排序),不如使用 collections.Counter()
;这不必创建中间列表来计算输入:
from collections import Counter
counts = Counter(a)
您还没有真正指定您认为的 'histogram'。假设您想在终端上执行此操作:
width = 120 # Adjust to desired width
longest_key = max(len(key) for key in counts)
graph_width = width - longest_key - 2
widest = counts.most_common(1)[0][1]
scale = graph_width / float(widest)
for key, size in sorted(counts.items()):
print('{}: {}'.format(key, int(size * scale) * '*'))
演示:
>>> from collections import Counter
>>> a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
>>> counts = Counter(a)
>>> width = 120 # Adjust to desired width
>>> longest_key = max(len(key) for key in counts)
>>> graph_width = width - longest_key - 2
>>> widest = counts.most_common(1)[0][1]
>>> scale = graph_width / float(widest)
>>> for key, size in sorted(counts.items()):
... print('{}: {}'.format(key, int(size * scale) * '*'))
...
a: *********************************************************************************************
b: **********************************************
c: **********************************************************************
d: ***********************
e: *********************************************************************************************************************
在 numpy.histogram()
and matplotlib.pyplot.hist()
函数中可以找到更复杂的工具。这些为您进行统计,matplotlib.pyplot.hist()
还为您提供图形输出。
使用 Pandas
很容易。
import pandas
from collections import Counter
a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
letter_counts = Counter(a)
df = pandas.DataFrame.from_dict(letter_counts, orient='index')
df.plot(kind='bar')
请注意 Counter
正在计算频率,因此我们的绘图类型是 'bar'
而不是 'hist'
。
正如@notconfusing 上面指出的,这可以用 Pandas 和 Counter 来解决。如果出于 任何原因您不需要使用 Pandas 您可以仅 matplotlib
使用以下代码中的函数:
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
letter_counts = Counter(a)
def plot_bar_from_counter(counter, ax=None):
""""
This function creates a bar plot from a counter.
:param counter: This is a counter object, a dictionary with the item as the key
and the frequency as the value
:param ax: an axis of matplotlib
:return: the axis wit the object in it
"""
if ax is None:
fig = plt.figure()
ax = fig.add_subplot(111)
frequencies = counter.values()
names = counter.keys()
x_coordinates = np.arange(len(counter))
ax.bar(x_coordinates, frequencies, align='center')
ax.xaxis.set_major_locator(plt.FixedLocator(x_coordinates))
ax.xaxis.set_major_formatter(plt.FixedFormatter(names))
return ax
plot_bar_from_counter(letter_counts)
plt.show()
哪个会产生
在python
中制作字符直方图的简单有效方法
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
a = []
count =0
d = dict()
filename = raw_input("Enter file name: ")
with open(filename,'r') as f:
for word in f:
for letter in word:
if letter not in d:
d[letter] = 1
else:
d[letter] +=1
num = Counter(d)
x = list(num.values())
y = list(num.keys())
x_coordinates = np.arange(len(num.keys()))
plt.bar(x_coordinates,x)
plt.xticks(x_coordinates,y)
plt.show()
print x,y
这里有一个简洁的全pandas方法:
a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
pd.Series(a).value_counts().plot('bar')
使用 numpy
使用 numpy 1.9 或更高版本:
import numpy as np
a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
labels, counts = np.unique(a,return_counts=True)
这可以使用以下方法绘制:
import matplotlib.pyplot as plt
ticks = range(len(counts))
plt.bar(ticks,counts, align='center')
plt.xticks(ticks, labels)
这是前一段时间的事了,所以我不确定你是否还需要帮助,但其他人可能需要帮助,所以我在这里。如果你被允许使用 matplotlib,我认为有一个更简单的解决方案!
a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
import matplotlib.pyplot as plt
plt.hist(a) #gives you a histogram of your array 'a'
plt.show() #finishes out the plot
这应该能为您提供一个漂亮的直方图!如果您愿意,还可以进行更多编辑来清理图表
我有一个字符串列表:
a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
我想制作一个直方图来显示字母的频率分布。我可以使用以下代码制作一个包含每个字母计数的列表:
from itertools import groupby
b = [len(list(group)) for key, group in groupby(a)]
如何制作直方图?我可能在列表 a
.
查看 matplotlib.pyplot.bar
。还有 numpy.histogram
如果你想要更宽的垃圾箱,它会更灵活。
与其使用 groupby()
(这需要对输入进行排序),不如使用 collections.Counter()
;这不必创建中间列表来计算输入:
from collections import Counter
counts = Counter(a)
您还没有真正指定您认为的 'histogram'。假设您想在终端上执行此操作:
width = 120 # Adjust to desired width
longest_key = max(len(key) for key in counts)
graph_width = width - longest_key - 2
widest = counts.most_common(1)[0][1]
scale = graph_width / float(widest)
for key, size in sorted(counts.items()):
print('{}: {}'.format(key, int(size * scale) * '*'))
演示:
>>> from collections import Counter
>>> a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
>>> counts = Counter(a)
>>> width = 120 # Adjust to desired width
>>> longest_key = max(len(key) for key in counts)
>>> graph_width = width - longest_key - 2
>>> widest = counts.most_common(1)[0][1]
>>> scale = graph_width / float(widest)
>>> for key, size in sorted(counts.items()):
... print('{}: {}'.format(key, int(size * scale) * '*'))
...
a: *********************************************************************************************
b: **********************************************
c: **********************************************************************
d: ***********************
e: *********************************************************************************************************************
在 numpy.histogram()
and matplotlib.pyplot.hist()
函数中可以找到更复杂的工具。这些为您进行统计,matplotlib.pyplot.hist()
还为您提供图形输出。
使用 Pandas
很容易。
import pandas
from collections import Counter
a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
letter_counts = Counter(a)
df = pandas.DataFrame.from_dict(letter_counts, orient='index')
df.plot(kind='bar')
请注意 Counter
正在计算频率,因此我们的绘图类型是 'bar'
而不是 'hist'
。
正如@notconfusing 上面指出的,这可以用 Pandas 和 Counter 来解决。如果出于 任何原因您不需要使用 Pandas 您可以仅 matplotlib
使用以下代码中的函数:
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
letter_counts = Counter(a)
def plot_bar_from_counter(counter, ax=None):
""""
This function creates a bar plot from a counter.
:param counter: This is a counter object, a dictionary with the item as the key
and the frequency as the value
:param ax: an axis of matplotlib
:return: the axis wit the object in it
"""
if ax is None:
fig = plt.figure()
ax = fig.add_subplot(111)
frequencies = counter.values()
names = counter.keys()
x_coordinates = np.arange(len(counter))
ax.bar(x_coordinates, frequencies, align='center')
ax.xaxis.set_major_locator(plt.FixedLocator(x_coordinates))
ax.xaxis.set_major_formatter(plt.FixedFormatter(names))
return ax
plot_bar_from_counter(letter_counts)
plt.show()
哪个会产生
在python
中制作字符直方图的简单有效方法import numpy as np
import matplotlib.pyplot as plt
from collections import Counter
a = []
count =0
d = dict()
filename = raw_input("Enter file name: ")
with open(filename,'r') as f:
for word in f:
for letter in word:
if letter not in d:
d[letter] = 1
else:
d[letter] +=1
num = Counter(d)
x = list(num.values())
y = list(num.keys())
x_coordinates = np.arange(len(num.keys()))
plt.bar(x_coordinates,x)
plt.xticks(x_coordinates,y)
plt.show()
print x,y
这里有一个简洁的全pandas方法:
a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
pd.Series(a).value_counts().plot('bar')
使用 numpy
使用 numpy 1.9 或更高版本:
import numpy as np
a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
labels, counts = np.unique(a,return_counts=True)
这可以使用以下方法绘制:
import matplotlib.pyplot as plt
ticks = range(len(counts))
plt.bar(ticks,counts, align='center')
plt.xticks(ticks, labels)
这是前一段时间的事了,所以我不确定你是否还需要帮助,但其他人可能需要帮助,所以我在这里。如果你被允许使用 matplotlib,我认为有一个更简单的解决方案!
a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
import matplotlib.pyplot as plt
plt.hist(a) #gives you a histogram of your array 'a'
plt.show() #finishes out the plot
这应该能为您提供一个漂亮的直方图!如果您愿意,还可以进行更多编辑来清理图表