首页 > 解决方案 > 用字符串键和数值绘制 python 字典

问题描述

我正在尝试用{'file/path':number of files matching pattern}. 根据Plotting a python dict in order of key values这应该可以工作,但是我也意识到我的 x 值不是整数,所以可能是这种情况,但我无法找到 x 轴是字符串而 y 是的示例对应的编号,

代码

import os
import re

import numpy as np
import matplotlib.pyplot as plt


def find_pattern(root_dir,keyword):
    out = {}
    pattern = re.compile(keyword)
    for filepath, subdirs, files in os.walk(root_dir):
        for filename in files:
            if pattern.match(filename):
                if filepath not in out:
                    out[filepath] = 1
                else:
                    out[filepath] = out[filepath] + 1
    width = 1.0
    print(out)
    plt.bar(out.keys(), out.values(), width, color='g')
    plt.show()
    return out

find_pattern('/Users/vector8188/AlgorithmAnalysisPython', '^(.(?!.*\.css$|.*\.html))*$')`

出字典的内容

`out = {'/Users/vector8188/AlgorithmAnalysisPython/.git/objects/28': 1, '/Users/vector8188/AlgorithmAnalysisPython/.git/objects/9a': 1, '/Users/vector8188/AlgorithmAnalysisPython/.git/objects/22': 1
}`

错误:

Traceback (most recent call last):
  File "apple_test.py", line 70, in <module>
    find_pattern('/Users/vector8188/AlgorithmAnalysisPython', '^(.(?!.*\.css$|.*\.html))*$')
  File "apple_test.py", line 66, in find_pattern
    plt.bar(out.keys(), out.values(), width, color='g')
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/pyplot.py", line 2515, in bar
    ret = ax.bar(left, height, width=width, bottom=bottom, **kwargs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/axes.py", line 5053, in bar
    self.add_patch(r)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/axes.py", line 1562, in add_patch
    self._update_patch_limits(p)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/axes.py", line 1580, in _update_patch_limits
    xys = patch.get_patch_transform().transform(vertices)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/patches.py", line 576, in get_patch_transform
    self._update_patch_transform()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/patches.py", line 569, in _update_patch_transform
    bbox = transforms.Bbox.from_bounds(x, y, width, height)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/transforms.py", line 821, in from_bounds
    return Bbox.from_extents(x0, y0, x0 + width, y0 + height)
TypeError: cannot concatenate 'str' and 'float' objects

标签: pythonmatplotlib

解决方案


您正在运行在 python 3 中为 python 2 编写的代码。

在 python 3 中,您应该首先将键和值转换为列表:

plt.bar(list(out.keys()), list(out.values()), width, color='g', ec="k")

推荐阅读