如何从Python中的字符串列表中创建直方图?

Gra*_*ray 27 python string histogram

我有一个字符串列表:

a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
Run Code Online (Sandbox Code Playgroud)

我想制作一个直方图来显示字母的频率分布.我可以使用以下代码创建一个包含每个字母数的列表:

from itertools import groupby
b = [len(list(group)) for key, group in groupby(a)]
Run Code Online (Sandbox Code Playgroud)

如何制作直方图?我可能在列表中有一百万个这样的元素a.

not*_*ing 41

非常容易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')
Run Code Online (Sandbox Code Playgroud)

请注意,Counter正在进行频率计数,因此我们的绘图类型'bar'不是'hist'.

字母直方图

  • 很好,尽管使用“系列”对象代替“数据帧”可能更简单,并且避免了图中的虚假“ 0”:`pandas.Series(Counter(a))。plot(kind ='bar')` 。 (2认同)

dra*_*ock 17

这是一种简洁的全熊猫方法:

a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
pd.Series(a).value_counts().plot('bar')
Run Code Online (Sandbox Code Playgroud)

计数条形图


Ram*_*nez 9

由于@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()
Run Code Online (Sandbox Code Playgroud)

哪个会产生 在此输入图像描述


Mar*_*ers 8

而不是使用groupby()(需要对输入进行排序),使用collections.Counter(); 这不需要创建中间列表来计算输入:

from collections import Counter

counts = Counter(a)
Run Code Online (Sandbox Code Playgroud)

你还没有真正指定你认为是'直方图'的东西.让我们假设您想在终端上执行此操作:

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) * '*'))
Run Code Online (Sandbox Code Playgroud)

演示:

>>> 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: *********************************************************************************************************************
Run Code Online (Sandbox Code Playgroud)

更复杂的工具都在发现numpy.histogram()和matplotlib.pyplot.hist()功能.这些为您matplotlib.pyplot.hist()提供统计,同时为您提供图形输出.


G M*_*G M 5

使用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)
Run Code Online (Sandbox Code Playgroud)

可以使用以下方法绘制:

import matplotlib.pyplot as plt 
ticks = range(len(counts))
plt.bar(ticks,counts, align='center')
plt.xticks(ticks, labels)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述