python - How can I use a nested dict keys as categorical variables to plot them using matplotlib?
问题描述
I am used to plotting stuff using ggplot
in R and I am struggling to visualize time series data stored in nested dicts
in Python using matplotlib
. Particularly, I would like to change colour and other plotting properties based on the "keys" of the dicts as categorical variables.
Here's a very simple example of what it looks like my nested dict:
mydict = {'subdict1': {'test_1': {'trial_1': np.array([[np.arange(0.0, 1.0, 0.01)],
[np.sin(2*np.pi*np.arange(0.0, 1.0, 0.01))]]),
'trial_2': np.array([[np.arange(0.0, 1.0, 0.01)],
[np.sin(3*np.pi*np.arange(0.0, 1.0, 0.01))]])},
'test_2': {'trial_1': np.array([[np.arange(0.0, 1.0, 0.01)],
[np.sin(4*np.pi*np.arange(0.0, 1.0, 0.01))]]),
'trial_2': np.array([[np.arange(0.0, 1.0, 0.01)],
[np.sin(5*np.pi*np.arange(0.0, 1.0, 0.01))]])}}}
I would like to easily make plots of the arrays, but using the test_n
key dict to colour or shape lines. The following code plots the example arrays but with a different colour for each iteration in the for loop:
fig, ax = plt.subplots(1)
for x in mydict.keys():
for y in mydict[x].keys():
for z in mydict[x][y].keys():
ax.plot(mydict[x][y][z][0][0], mydict[x][y][z][1][0])
I am aware of other possibilities using seaborn
or pandas. However, my nested dicts
are complex and contain many different arrays, so I am not sure if storing all the data to a data_frame
format would be a good idea?.
Alternatively (although this may be a different question?), I would like to know what would be the recommended way to convert my nested dict to an R object in order to take advantage of the categorical mapping functionalities of R's ggplot.
解决方案
也许您想将所有颜色设置为相同z
?
fig, ax = plt.subplots(1)
colors = iter(plt.rcParams["axes.prop_cycle"].by_key()['color'])
for x in mydict.keys():
for y in mydict[x].keys():
c = next(colors)
for z in mydict[x][y].keys():
ax.plot(mydict[x][y][z][0][0], mydict[x][y][z][1][0], color=c, label=z)
ax.legend()
plt.show()
推荐阅读
- python - 如何使用 get_FOO_display() 在 Django 中访问未实例化的模型
- vue.js - VUE:编译远程组件有什么安全友好的方法吗?
- informatica - Informatica 电力交换
- amazon-web-services - AWS:将作业参数值从 Step 函数传递给 Glue 作业
- angular-material - 在 Angular 中找不到库名?
- delphi - Delphi - ADVFN 登录问题
- c - 为什么它不显示while循环中的输出?
- android-studio - 获取嵌套列表值并将其添加到按钮文本
- c# - 我应该发布购物车项目的更改吗
- kotlin - 协程作用域构建器流程如何工作