python-分析json数据绘图
#数据分组groupby
from itertools import groupby
import pygal
import json
import math
filename = 'E:\CSDN\《Python编程》源代码⽂件-更新\《Python编程》源代码⽂件\chapter_16\\btc-master (16.2)\\btc_close_2017.json' with open(filename) as f:
warnier方法btc_data = json.load(f) #读取⽹络⽤loads
dates = []
months = []
weeks = []
weekdays = []java反序列化漏洞原理
closes = []
for btc_dict in btc_data:
dates.append(btc_dict['date'])
months.append(int(btc_dict['month']))
weeks.append(int(btc_dict['week']))
做私人网站的好处web服务器种类weekdays.append(btc_dict['weekday'])
closes.append(int(float(btc_dict['close'])))
# 创建绘线的实列,x_label_rotation=20 让X轴上的时间顺时针旋转20°,show_minor_x_labels=False不必显⽰所有的X轴坐标
line_chart = pygal.Line(x_label_rotation=20, show_minor_x_labels=False)
line_chart.x_labels = dates
N=20 #x坐标每20 天显⽰⼀次
line_chart.x_labels_major = dates[::N]
line_chart.add('收盘价', closes)
der_to_file('收盘价折现图(¥).svg')
#消除⾮线性的趋势——对数变换
line_chart1 = pygal.Line(x_label_rotation=20, show_minor_x_labels=False)
line_chart1.title = '收盘价对数变换(¥)'
line_chart1.x_labels = dates
N = 20 # x坐标每20 天显⽰⼀次
line_chart1.x_labels_major = dates[::N]
chose_log = [math.log10(_) for _ in closes]#这⾥是以10为低的对数函数(半对数变换)
line_chart1.add('log收盘价', chose_log)
der_to_file('收盘价对数变换折现图(¥).svg')
#绘图⽅法
def draw_line(x_data,y_data, title, y_legeng):
xy_map = []
#将x,y数据合并,分组再排序,然后求出每组平均值
for x, y in groupby(sorted(zip(x_data, y_data)), key=lambda _: _[0]):
y_list = [v for _, v in y]
xy_map.append([x, sum(y_list)/len(y_list)])
x_unique, y_mean = [*zip(*xy_map)] #数据分离
python请求并解析json数据line_chart = pygal.Line()
英文名snowy什么意思line_chart.title = title
line_chart.x_labels = x_unique
line_chart.add(y_legeng, y_mean)
der_to_file(title+'.svg')
return line_chart
idx_month = dates.index('2017-12-01')
line_chart_month = draw_line(months[:idx_month], closes[:idx_month],'收盘价⽉,⽇均值(¥)', '⽉,⽇均值')
line_chart_month
idx_week = dates.index('2017-12-11')
line_chart_week = draw_line(weeks[1:idx_month], closes[1:idx_month],'收盘价周,⽇均值(¥)', '周,⽇均值')
line_chart_week
idx_weekday = dates.index('2017-12-11')
wd = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
weeks_int = [wd.index(w) + 1 for w in weekdays[1:idx_weekday]]
line_chart_weekday = draw_line(weeks_int,closes[1:idx_weekday],'收盘价星期均值(¥)', '星期均值')
line_chart_weekday.x_labels = ['星期⼀', '星期⼆', '星期三', '星期四', '星期五', '星期六', '星期⽇']
line_der_to_file('收盘价星期均值(¥).svg')
#将⼏个svg和再⼀个⽹页上
with open('收盘价Dashboard.html', 'w', encoding='utf8') as html_file:
html_file.write('<html><head><title>收盘价Dashboard</title><metacharset="utf-8"></<head><body>\n') for svg in ['收盘价周,⽇均值(¥).svg', '收盘价对数变换折现图(¥).svg',
'收盘价折现图(¥).svg', '收盘价星期均值(¥).svg', '收盘价⽉,⽇均值(¥).svg']:
html_file.write(' < <object type="image/svg+xml" data="{0}" height=500></object>\n'.format(svg)) # 1 html_file.write('</body></html>')
源码及其数据来⾃《Python编程从⼊门到实践》第16章 相信内容请买书或搜索扫描版。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论