首页 > 解决方案 > 如何用括号和逗号而不是冒号来可视化字典

问题描述

这是需要在条形图中获取的一小部分数据以及我尝试使用的代码。但是括号和括号中的“,”而不是“:”使我无法以任何方式完成它。(我想制作一个条形图,显示链接显示的时间,例如:'http://www.wikidata.org/entity/Q31855 5,'http://www.wikidata.org/entity/Q5',24 .)

a_dictionary = {'class vs. total number of instances of the class': [('http://www.wikidata.org/entity/Q31855',
   5),
  ('http://www.wikidata.org/entity/Q5', 24),
  ('http://www.wikidata.org/entity/Q9388534', 25)],
 'property vs. total number of distinct objects in triples using the property': [('http://www.wikidata.org/prop/direct/P800',
   1),
  ('https://w3id.org/artchives/wikidataReconciliation', 1),
  ('http://www.w3.org/ns/prov#wasInfluencedBy', 2),
  ('https://w3id.org/artchives/publicationStage', 2),
  ('https://w3id.org/artchives/hasSecondLink', 2)]}


keys = a_dictionary.keys()
values = a_dictionary.values()

plt.bar(keys, values)

这是随之而来的错误:

TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U39') dtype('<U39') dtype('<U39')

有人想用这种类型的数据制作条形图吗?

如果我使用有人在评论中建议的代码,我会收到一个错误,我认为原因是链接和数字周围的 (),因为在键和之间有 ',' 而不是 ':'价值。有没有人有办法解决吗?

标签: pythondictionarydata-visualizationvisualization

解决方案


重新格式化字典的缩进显示:

a_dictionary = {'class vs. total number of instances of the class':
                    [('http://www.wikidata.org/entity/Q31855', 5),
                     ('http://www.wikidata.org/entity/Q5', 24),
                     ('http://www.wikidata.org/entity/Q9388534', 25)],
                'property vs. total number of distinct objects in triples using the property':
                    [('http://www.wikidata.org/prop/direct/P800', 1),
                     ('https://w3id.org/artchives/wikidataReconciliation', 1),
                     ('http://www.w3.org/ns/prov#wasInfluencedBy', 2),
                     ('https://w3id.org/artchives/publicationStage', 2),
                     ('https://w3id.org/artchives/hasSecondLink', 2)]}

因此,在此示例中,只有 2 个具有相应值的键。这些值是元组列表。

绘制这样一个字典的一种方法是为每个键创建一个子图,每个子图包含元组中存在的信息的条形图。

由于字符串很长,可以编写一个专用函数来拆分它们。另一个(或:附加)选项是旋转字符串。

以下代码显示了一个帮助您入门的示例:

import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

def split_url(url_string):
    splitted = url_string.split('/')
    res = ''
    length = 0
    for s in splitted[:-1]:
        length += len(s)
        if length < 9:
            res += s + '/'
        else:
            res += s + '/\n'
            length = 0
    res += '\n#'.join(splitted[-1].split('#'))
    return res

fig, axes = plt.subplots(ncols=len(a_dictionary), figsize=(20, 5),
                         gridspec_kw={'width_ratios': [len(v) for v in a_dictionary.values()]})
for (key, occurrences), ax in zip(a_dictionary.items(), axes):
    ax.bar([split_url(url) for url, num in occurrences],
           [num for label, num in occurrences], color='turquoise')
    ax.set_title(key)
    ax.yaxis.set_major_locator(MaxNLocator(integer=True))
    # ax.tick_params(axis='x', rotation=90)
plt.tight_layout()
plt.show()

示例图


推荐阅读