首页 > 解决方案 > 从 Python 中的嵌套列表制作直方图

问题描述

我有以下列表,我喜欢用这些数据制作直方图,但我不知道该怎么做。

finished = [('https', 38), ('on', 33), ('with', 32), ('model', 28), ('com', 26), ('evaluation', 19), ('detection', 19), ('br', 18), ('models', 18), ("href='g3doc", 17), ('trained', 17)]

我尝试了以下方法:

import matplotlib.pyplot as plt
z=0
for i in finished:

    plt.hist(finished[z], bins = range(38))
    z=z+1
plt.show()

我总是对标签和值感到困惑。

谢谢你,祝你有美好的一天

标签: pythonlist

解决方案


我会使用这样的条形图:

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

finished = [('https', 38), ('on', 33), ('with', 32), ('model', 28), ('com', 26), ('evaluation', 19), ('detection', 19), ('br', 18), ('models', 18), ("href='g3doc", 17), ('trained', 17)]
names = list(f[0] for f in finished)
values = list(f[1] for f in finished)

y_pos = np.arange(len(finished))

plt.figure(figsize=(20,10))
plt.bar(y_pos, values, align='center', alpha=0.5)
plt.xticks(y_pos, names)
plt.ylabel('Values')
plt.title('Word usage')

plt.show()

样本

使用不同的数据格式可能会更好。但这适用于您的示例数据。


推荐阅读