【问题标题】:Generate Plot from dictionary data. The elegant way从字典数据生成绘图。优雅的方式
【发布时间】:2020-02-05 17:45:50
【问题描述】:

您好,我生成了一个如下所示的 json 文件。

{
        "1": {
            "t1": 1580922111616263,
            "t2": 1580922111625000,
            "t3": 1580922111625632,
            "t4": 1580922112126443,
            "t5": 1580922112131123
        },
        "2": {
            "t1": 1580922112632761,
            "t2": 1580922112655000,
            "t3": 1580922112659807,
            "t4": 1580922113161233,
            "t5": 1580922113162554
        },

...............................
        "28": {
            "t1": 1580922139740049,
            "t2": 1580922139764000,
            "t3": 1580922139770782,
            "t4": 1580922140274371,
            "t5": 1580922140288827
        },
        "29": {
            "t1": 1580922140792481,
            "t2": 158092214085900,
            "t3": 1580922140860625,
            "t4": 1580922141363088,
            "t5": 1580922141368971
        }
    }

我想创建 4 个不同的地块。每个图代表一个时间段。

first plot => time period t1 - t2
second plot => t2-t3
third plot => t3 - t4
fourth plot => t4-t5

每个图都应该包含每个键的每个时间段。所以每个情节总共应该有 29 行。 哪个是最优雅的实现方式?

import json
import matplotlib.pyplot as plt

with open('/home/test.json', 'r') as outfile:
    file = json.load(outfile)

    plt.figure()
    for k, v in file.items():
        for z, x in v.items():
            if z == 't1':
                t1 = x
            elif z == 't2':
                t2 = x
            elif z == 't3':
                t3 = x
            elif z == 't4':
                t4 = x
            elif z == 't5':
                t5 = x

        xvals = [t2, t1]
        yvals = [k, k]

        plt.plot(xvals, yvals)

plt.show()

【问题讨论】:

  • 你有一个不优雅的工作示例吗?您在哪里卡住了,或者出了什么问题?
  • 为什么会有matlab标签?
  • @Aaron 当然!我的代码大多不优雅!如果你有时间,请检查更新

标签: python dictionary matplotlib data-science


【解决方案1】:

将您的数据存储在data 变量中。

试试下面的代码

def get_diff():
    diff_list = {}
    time_list = ['t1','t2','t3','t4','t5']
    for key in data:
        diff_list[key] = []
        for i in range(1,5):
            diff_list[key].append(data[key][time_list[i]]-data[key][time_list[i-1]])
    return pd.DataFrame(diff_list).T

y = get_diff()

plt.plot(y.index,y['0'],'--')
plt.plot(y.index,y['1'],'--')
plt.plot(y.index,y['2'],'--')
plt.plot(y.index,y['3'],'--')
plt.show()

【讨论】:

    猜你喜欢
    • 2015-03-22
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    相关资源
    最近更新 更多