0

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.

AJMA
  • 1,134
  • 2
  • 13
  • 28
  • 1
    What's the question, given that the code you show apparently gives you the correct result? Did I miss something? – ImportanceOfBeingErnest Nov 26 '18 at 16:53
  • I would like the plot to be coloured by `test_1` and `test_2` keys (i.e. only 2 colours). It currently gives a different colour for each line plotted. – AJMA Nov 26 '18 at 16:56

1 Answers1

1

Maybe you want to set the color to be same for all 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()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712