python - 如何用括号和逗号而不是冒号来可视化字典
问题描述
这是需要在条形图中获取的一小部分数据以及我尝试使用的代码。但是括号和括号中的“,”而不是“:”使我无法以任何方式完成它。(我想制作一个条形图,显示链接显示的时间,例如:'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')
有人想用这种类型的数据制作条形图吗?
如果我使用有人在评论中建议的代码,我会收到一个错误,我认为原因是链接和数字周围的 (),因为在键和之间有 ',' 而不是 ':'价值。有没有人有办法解决吗?
解决方案
重新格式化字典的缩进显示:
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()
推荐阅读
- javascript - 在 React-app 中未定义变量 no-undef
- testing - 如何在测试中更详细?
- python-3.x - 如何在python中与分叉进程共享变量?
- react-native - 适用于 iOS、Android 和 Web 的 Okta 集成
- javascript - 如何通过单击单选按钮切换 div?
- linkedin - LinkedIn 视频分析时间范围
- python - Python:运行一个程序来反转任何给定单词的顺序
- excel - 从列表优化中搜索文件名
- sql - 使用 Oracle SQL 用正则表达式拆分字符串
- angular - 有没有办法,我可以在 Angular HTTP 拦截器中阻止 HTTP 请求,直到其他请求成功?