KM Goh KM Goh - 1 year ago 74
JSON Question

Plotting graph of text file with strings and integers at the same lines

I am trying to plot a graph using a txt data file of followig arrangement way:

{"alpha": 77.6, "beta": 135, "gamma": 342, "delta": 86.3}

{"alpha": 77.3, "beta": 140, "gamma": 332, "delta": 82.3}


(300++ lines below with similar arrangements)

A normal table should work with the following code(and that's what I want) :

def get_points(x,y):
a = 'xyz/examples.txt'
data = np.genfromtxt(a,delimiter=',',skip_header=1)
x_axis = data[:,x]
y_axis = data[:,y]


since I am trying to make a code which you can change the x- and y- axis as you like. However, it won't work in this case since the headers and the values are at the same lines for each of them.

May I know if there is any way to remove the headers or extract the integers out of the data etc?Thanks!!!

Answer Source

The following snippet should work for your purpose.

import numpy as np
import matplotlib.pyplot as plt
from json import loads

data = {}
def get_points(x, y):
    a = 'xyz/examples.txt'
    with open(a, 'r') as f:
        for line in f:
            new_dict = loads(line.strip())
            for k in new_dict:
                if k in data:
                    data[k] = [float(new_dict[k])]

    array = np.array([data[x], data[y]])
    plt.plot(array[0], array[1])

get_points('alpha', 'beta')

Since each line has the same format, you can convert each one to dictionary and append for each channel its value. This will give you a sort dictionary where the key is the channel and the value is a list of values (in the right order). The only change is that you have to reference the channels by their names and not index, since the dictionary is unsorted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download