简体   繁体   English

使用 python 库可视化 JSON 数据

[英]Visualising JSON data using python libraries

I am visualising the json data using mathplotlib and pandas我正在使用 mathplotlib 和 pandas 可视化 json 数据

  {
    "data_point": 0,
    "Add": 2977780,
    "Add_num": 38595
  },
  {
    "data_point": 1,
    "Add": 2809086,
    "Add_num": 36534
  },
  {
    "data_point": 2,
    "Add": 2825428,
    "Add_num": 36534
  },
  {
    "data_point": 3,
    "Add": 2826861,
    "Add_num": 36564
  }]

This is the data now i want to draw a graph with y-axis as value obtained from division of "Add" and "Add_num" (Add/Add_num) and "data_point" as x-axis.这是现在我想绘制一个图表,其中 y 轴作为从"Add""Add_num" (Add/Add_num)和"data_point"作为 x 轴的除法获得的值。 Is there a way to do this in python code or I need to process json data to add Add_avg field in json file(ie Add_avg = Add/Add_num)有没有办法在 python 代码中执行此操作,或者我需要处理 json 数据以在 json 文件中添加Add_avg字段(即 Add_avg = Add/Add_num)

Code to draw the graph绘制图形的代码

import json
import pandas as pd

a_file = open("./data.json", "r")
json_object = json.load(a_file)
a_file.close()
df = pd.DataFrame(json_object)
df.plot(x='data_point', y='Add',color='maroon', marker='o')
df.plot(x='data_point', y='Add_num',color='maroon', marker='o')

You can use matplotlib directly to plot, then you can do the calculations while plotting.您可以直接使用matplotlib到 plot,然后您可以在绘图时进行计算。 Or you can indeed add another column:或者您确实可以添加另一列:

import json
import pandas as pd
from matplotlib import pyplot as plt

js = """[ {
    "data_point": 0,
    "Add": 2977780,
    "Add_num": 38595
  },
  {
    "data_point": 1,
    "Add": 2809086,
    "Add_num": 36534
  },
  {
    "data_point": 2,
    "Add": 2825428,
    "Add_num": 36534
  },
  {
    "data_point": 3,
    "Add": 2826861,
    "Add_num": 36564
  }]"""

# Use loads instead of load since in my case the json is a string:
df = pd.DataFrame(json.loads(js))

# plot:
fig, ax = plt.subplots(1)
ax.plot(df['data_point'], df['Add']/df['Add_num'])
plt.show()

Or add a new column:或者添加一个新列:

df['Add_avg'] = df['Add']  / df['Add_num']
df.plot(x='data_point', y='Add_avg', color='maroon', marker='o')
plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM