使用 python 库可视化 JSON 数据

Visualising JSON data using python libraries

我正在使用 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
  }]

这是我现在要绘制的数据,其中 y 轴作为从 "Add""Add_num" (Add/Add_num) 和 "data_point" 相除获得的值作为 x 轴。有没有办法在 python 代码中执行此操作,或者我需要处理 json 数据以在 json 文件中添加 Add_avg 字段(即 Add_avg = Add/Add_num)

绘制图表的代码

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

可以直接用matplotlib画图,边画边计算。或者您确实可以添加另一列:

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

或添加新列:

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