Home > OS >  Multi-Line Graph: Stuck with the json-dict format for the lines
Multi-Line Graph: Stuck with the json-dict format for the lines

Time:01-09

Hello I am totally new to using Python for data visualisation, I have this json response:

{
"max365": 83.87,
"current365": 83.87,
"min365": 75.29,

"max180": 76.94,
"current180": 76.94,
"min180": 56.43,

"max90": 98.66,
"current90": 98.66,
"min90": 63.29,

"max30": 138.14,
"current30": 136,
"min30": 66.77,

"max14": 156.93,
"current14": 122.88,
"min14": 72.56,

"max7": 168.9,
"current7": 122.68,
"min7": 74.08,

"max0": 267.5,
"current0": 81.28,
"min0": 36.07 }

max, current and min are the lines I would like to plot on a multi-line graph, but I am struggling with the data in this date/time-grouping format with the response.

I've added a screenshot of a graph here that I am essentially trying to reverse engineer:

Multi-line graph - "Volatility Cone"

I've seen some useful posts for generic line graphs, but my issue here is mostly linking all the max/current/mins onto their own lines whilst I have 0/7/14/30/90/180/365 grouping/intersecting each of them in the response.

Hope I've explained it well enough. Any help would be greatly appreciated.

CodePudding user response:

Python standard library has a enter image description here

… and here it is the code — I'd like to underline that we need to split the labels to get out the real label and the sequence info(¿are the numbers time? I made an educated guess), so for each label we construct a list of lists, each element a time and a value, then we sort the lists inside each labelled list and finally we plot the three lines.

 from matplotlib.pyplot import subplots
 from json import loads
 
 def split_num(s):
     num = []
     for c in reversed(s):
         if c.isdigit():
             num  = c
         else:
             break
     if num:
         return s[:-len(num)], ''.join(reversed(num))
     else:
         return s, ''
 
 json = '''{
     "max365": 83.87,"current365": 83.87,"min365": 75.29,
     "max180": 76.94,"current180": 76.94,"min180": 56.43,
     "max90": 98.66,"current90": 98.66,"min90": 63.29,
     "max30": 138.14,"current30": 136,"min30": 66.77,
     "max14": 156.93,"current14": 122.88,"min14": 72.56,
     "max7": 168.9,"current7": 122.68,"min7": 74.08,
     "max0": 267.5,"current0": 81.28,"min0": 36.07 }'''
 jdict = loads(json)
 
 data = {}
 for k in jdict:
     name, num = split_num(k)
     data[name] = data.setdefault(name, [])   [[int(num), float(jdict[k])]]
 for k in data: data[k] = sorted(data[k])
 
 fig, ax = subplots()
 for k in data:
     ax.plot(*zip(*data[k]), label=k)
 ax.legend()
 fig.show()
  •  Tags:  
  • Related