python - 如何从字典中的字典创建子图条形图
问题描述
我需要制作以下字典的条形图的子图:dict1 = {44: {0: 0, 1: 1, 2: 0, 3: 3, 4: 6}, 45:{0: 1, 1: 4, 2: 2, 3: 0, 4: 0}}
This was my (not correct) code:
fig, ax = plt.subplots(2,1)
for nr in dict1:
ax[list(dict1.keys()).index(nr),1].plot(list(dict1[nr].keys()), list(dict1[nr].values()), kind='bar')
plt.tight_layout()
plt.show
你能帮我吗?提前致谢。
解决方案
问题中的代码有很多错误。两种选择:
Matplotlib 风格的绘图
import matplotlib.pyplot as plt
dict1 = {44: {0: 0, 1: 1, 2: 0, 3: 3, 4: 6}, 45:{0: 1, 1: 4, 2: 2, 3: 0, 4: 0}}
fig, axs = plt.subplots(len(dict1.keys()))
for (k, d), ax in zip(dict1.items(), axs):
ax.bar(*zip(*d.items()))
ax.set_title(k)
fig.tight_layout()
plt.show()
熊猫风格的绘图
import pandas as pd
import matplotlib.pyplot as plt
dict1 = {44: {0: 0, 1: 1, 2: 0, 3: 3, 4: 6}, 45:{0: 1, 1: 4, 2: 2, 3: 0, 4: 0}}
df = pd.DataFrame(dict1)
df.plot.bar(subplots=True)
plt.tight_layout()
plt.show()
推荐阅读
- ios - 使 ScrollView 中的滚动条在 SwiftUI 中始终可见
- c# - 如何使用 C# 或 Microsoft Graph 检查列表 Sharepoint 中添加的新项目
- android - 键盘关闭时来自 API 重置的颤动文本字段值
- assembly - 与屏幕上的其他元素组合打印
- microsoft-graph-api - 使用 Microsoft Graph API 向有效电子邮件地址授予权限时收到错误代码“noResolvedUsers”的 400 错误请求
- solr - Solr /更新处理程序
- c# - 在 Xamarin.Forms.Maps 中从 Android InfoWindow 中的自定义 pin 对象动态添加图像
- python - 如何使用 pandas 中的函数从给定列表中返回值?
- javascript - React js正则表达式查找以__开头和结尾的所有单词
- python - macOS 上的 pandas Swifter 防火墙