【问题标题】:Using dictionary to make a matplotlib graph?使用字典制作 matplotlib 图?
【发布时间】:2014-02-21 03:58:36
【问题描述】:

如果我有一个单词字典及其在字符串中出现的频率,例如:

{'hello': 3, 'how': 4, 'yes': 10, 'you': 11, 'days': 10, 'are': 20, 'ago': 11}

如何使用 matplotlib 制作条形图?我发现了一个以前的问题,它有一个看似不错的解决方案,但它对我不起作用 (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 值也是数字?我不确定。

【问题讨论】:

    标签: python dictionary matplotlib


    【解决方案1】:

    尝试将您的d.keys() 封装在list() 调用中:

    plt.bar(range(len(d)), d.values(), align="center")
    plt.xticks(range(len(d)), list(d.keys()))
    

    在 Python3 中,dict.keys() 不会直接返回键列表,而是返回一个生成器,它会在您使用时一次为您提供一个键。

    【讨论】:

    • 完美运行,谢谢!我会记住这就是 dict.keys() 的工作原理。
    • 这与我的问题不太相关,但是有什么办法可以自动化条形之间的空间,以便所有单词都可以放在 x 轴上(或者让单词去换行?)
    • @Howcan 也许你想把长词分成多行?
    【解决方案2】:

    " 上,有什么方法可以使条形之间的空间自动化,以便所有单词都可以放在 x 轴上(或者也许让单词换行?)"

    我会将长词分成多行,例如,'looooooooongWord''looooo-\noooong-\nWord'

    In [300]: d={'hello': 3, 'how': 4, 'yes': 10, 'you': 11, 'days': 10, 'are': 20, 'ago': 11, 'looooooooongWord': 10}
         ...: plt.bar(range(len(d)), d.values(), align="center")
         ...: plt.xticks(range(len(d)), [split_word(i) for i in d.keys()])
    

    其中split_word 定义为:

    In [595]: def split_word(s):
         ...:     n=6
         ...:     return '-\n'.join(s[i:i+n] for i in range(0, len(s), n))
         ...: split_word('looooooooongWord')
    Out[595]: 'looooo-\noooong-\nWord'
    

    【讨论】:

      猜你喜欢
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      相关资源
      最近更新 更多