Home > front end >  Graphing a dictionary with strange formatting in Python
Graphing a dictionary with strange formatting in Python

Time:02-18

I have a dictionary in python like so:

test={'fg':['1','2','3','4','5'],
'values':[np.array([5,6,7,8]),np.array([2,3,4,5]),np.array([6,5,4,3]),np.array([4,5,6,7]),np.array([1,2,3,4])],

What I'd like to do with this dictionary is make 5 overlayed line plots; one for each fg value, graphing the array of values in the corresponding item in the 'values' key over the number of units in the each of the 'values' arrays.

So, the first line graph would be for 'fg':'1', and would graph 5,6,7,8 as y values over 1,2,3,4 (the number of units in the array) as x values. The second line graph would be for 'fg':'2', and would graph 2,3,4,5 as y values over, again, 1,2,3,4 as x values. Please let me know if I can further clarify.

I'm not well versed in plotting dictionaries with this formatting so I don't even really know where to start. Any advice would be greatly appreciated!

CodePudding user response:

It's pretty straight forward. We can just loop over the values field in your dictionary and plot each of those entries:

# import libraries
import numpy as np
import matplotlib.pyplot as plt

# define your data
test={'fg':['1','2','3','4','5'],
'values':[np.array([5,6,7,8]),np.array([2,3,4,5]),np.array([6,5,4,3]),np.array([4,5,6,7]),np.array([1,2,3,4])]}

for values in test['values']: # iterate over all "values" entries
    x = np.arange(1, values.shape[0] 1)  # set up x-vector
    plt.plot(x, values, '-')  # plot
plt.legend(test['fg'])  # optionally add legend
plt.show()  # create plo  # create plot

CodePudding user response:

you can use zip:

for i, j in zip(test['fg'], test['values']):
    plt.plot(np.arange(len(j)) 1, j)
    plt.title(i)

CodePudding user response:

I came up with using the zip method to iterate test['fg'] and test['values'] at the same time. Try using the zip() method like this:

import numpy as np
test={'fg':
['1','2','3','4','5'],
'values':[np.array([5,6,7,8]),np.array([2,3,4,5]),np.array([6,5,4,3]),np.array([4,5,6,7]),np.array([1,2,3,4])],
for fgNum, valArray in zip(test['fg'],test['values']):
    # do your matplotlib stuff here
  • Related