Graphing A Dictionary With Strange Formatting In Python
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!
Answer
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
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module