如果我有一个单词字典和它们在字符串中的频率,例如:
{'hello': 3, 'how': 4, 'yes': 10, 'you': 11, 'days': 10, 'are': 20, 'ago': 11}
我如何使用 matplotlib 从中制作条形图?我发现了一个 previous question,它有一个看似好的解决方案,但它对我不起作用 ( python: plot a bar using matplotlib using a dictionary )
当我运行时
plt.bar(range(len(d)), d.values(), align="center")
plt.xticks(range(len(d)), d.keys())
我得到了错误
TypeError: 'dict_keys' object does not support indexing
我真的不知道我在哪里为我的字典编制索引。可能是因为在我从中获得代码的问题中,x 值也是数字?我不确定。
请您参考如下方法:
尝试将您的 d.keys() 包装在 list() 调用中:
plt.bar(range(len(d)), d.values(), align="center")
plt.xticks(range(len(d)), list(d.keys()))
在 Python3 中,dict.keys() 不直接返回键列表,而是返回一个生成器,它会在您使用时一次为您提供一个键。
