如何可视化含括号与逗号(而非冒号)结构的字典并生成柱状图?
解决Matplotlib柱状图绘制的字典数据格式问题
这个错误的根源很明确:你直接把包含元组列表的字典值传给了plt.bar(),但Matplotlib的柱状图要求y轴参数是数值数组,而不是嵌套的元组结构。我们需要先把字典里的(链接, 次数)元组拆分成独立的标签和数值列表,再进行可视化。
分步解决方案
- 拆解数据结构:遍历字典的每个键值对,把每个元组中的链接(x轴标签)和次数(y轴高度)分别提取出来。
- 分维度可视化:因为你的字典包含两个不同的统计维度(类实例数、属性关联对象数),用子图分开展示会更清晰。
- 优化标签显示:由于链接字符串较长,旋转x轴标签避免重叠。
完整可运行代码
import matplotlib.pyplot as plt # 你的原始数据 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行1列的子图布局,适配两个统计维度 fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(10, 8)) # 处理「类 vs 实例数」的可视化 class_items = a_dictionary['class vs. total number of instances of the class'] class_labels = [item[0] for item in class_items] class_counts = [item[1] for item in class_items] ax1.bar(class_labels, class_counts, color='#1f77b4') ax1.set_title('Class vs. Total Number of Instances') ax1.set_ylabel('Instance Count') # 旋转x轴标签,右对齐避免重叠 ax1.tick_params(axis='x', rotation=45, ha='right') # 处理「属性 vs 不同对象数」的可视化 property_items = a_dictionary['property vs. total number of distinct objects in triples using the property'] property_labels = [item[0] for item in property_items] property_counts = [item[1] for item in property_items] ax2.bar(property_labels, property_counts, color='#ff7f0e') ax2.set_title('Property vs. Total Number of Distinct Objects') ax2.set_ylabel('Distinct Object Count') ax2.tick_params(axis='x', rotation=45, ha='right') # 自动调整子图间距,防止元素重叠 plt.tight_layout() plt.show()
代码说明
- 我们用列表推导式
[item[0] for item in ...]和[item[1] for item in ...]分别提取链接标签和对应的次数数值,把嵌套结构转换成Matplotlib能识别的格式。 - 使用子图(
subplots)将两个不同的统计结果分开展示,避免信息混乱。 - 通过
tick_params旋转x轴标签并设置右对齐,解决长链接重叠的问题。 tight_layout()自动调整子图间距,让整体布局更美观。
如果你只需要可视化其中一个维度(比如只看类的实例数),可以只保留对应部分的代码即可。
内容的提问来源于stack exchange,提问作者dennisvl
相关产品推荐
相关产品推荐

