首页 > 解决方案 > 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.

标签: pythonrmatplotlibggplot2

解决方案


也许您想将所有颜色设置为相同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()

推荐阅读