【问题标题】:Multi-Line Graph: Stuck with the json-dict format for the lines多线图:使用 json-dict 格式的线条
【发布时间】:2022-01-08 00:56:27
【问题描述】:

您好,我是使用 Python 进行数据可视化的新手,我收到了这个 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 }

maxcurrentmin 是我想在多线图上绘制的线,但我正在努力处理这种日期/时间分组格式的数据以及响应。

我在这里添加了一个图表的屏幕截图,我实际上是在尝试逆向工程:

我已经看到了一些关于通用折线图的有用帖子,但我在这里的问题主要是将所有最大/当前/分钟链接到它们自己的线上,而我有 0/7/14/30/90/180/365 分组/在响应中与它们中的每一个相交。

希望我已经解释得足够好。任何帮助将不胜感激。

【问题讨论】:

    标签: python matplotlib graph data-visualization


    【解决方案1】:

    Python 标准库有一个json module,你只需要导入loads 方法,稍微按摩一下数据。

    ……这里是代码——我想强调一下,我们需要拆分标签以获取真实标签和序列信息(¿是数字时间吗?我做了一个有根据的猜测),所以对于每个标签我们构造一个列表列表,每个元素一个时间和一个值,然后我们对每个标签列表中的列表进行排序,最后绘制三行。

     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()
    

    【讨论】:

    • 非常感谢 - 我可以从您的图表中看出您的操作是正确的。然而,简单地运行您的代码,图表本身并没有显示给我,但我会尝试解决这个问题。
    • 解决方案适用于 Jupyter。
    • @GundamWing ፨我已经在交互式解释器中执行了代码,它“按原样”工作,但要让它作为脚本工作,你必须做两个小改动:①第一行,更改为from matplotlib.pyplot import subplots, show,②最后一行,更改为@ 987654328@(没有fig. 前置)。 HTH
    • 太棒了 - 非常感谢。
    猜你喜欢
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 2017-01-02
    • 2018-04-02
    相关资源
    最近更新 更多