#coding:utf-8
import pygal
import json
from itertools import groupby
dates,months,weeks,weekdays,close=[],[],[],[],[]
with open('btc_close_2017.json','r')as f:
btc_data=json.load(f)
for btc_dict in btc_data:
dates.append(btc_dict['date'])
months.append(int(btc_dict['month']))
weeks.append(int(btc_dict['week']))
weekdays.append(btc_dict['weekday'])
close.append(int(float(btc_dict['close'])))
def draw_line(x_data, y_data, title, y_legend):
xy_map = []
for x,y in groupby(sorted(zip(x_data, y_data)),key=lambda _:_[0]):
#print(x)
y_list= [v for _,v in y]
xy_map.append([x, sum(y_list) / len(y_list)])
x_unique, y_mean = [*zip(*xy_map)]
line_chart = pygal.Line()
line_chart.title = title
line_chart.x_labels = x_unique
line_chart.add(y_legend, y_mean)
line_chart.render_to_file(title+'.svg')
return line_chart
idx_month=dates.index('2017-12-01')
line_chart_month=draw_line(months[:idx_month],close[:idx_month],'title','legend')
line_chart_month
上面是照着书本打的...报错:TypeError: object of type 'int' has no len()
经测试
直接注释掉 line_chart.render_to_file(title+'.svg') 后正常
看来是写入文件时出了问题
又经测试
把months.append(int(btc_dict['month'])) 改为
months.append(btc_dict['month']) 后正常
猜想:列表里为int型变量作为x轴labels无法正常写入文件 应为字符型
测试代码如下:
import pygal
line_chart = pygal.Line()
line_chart.x_labels = [1,2]
line_chart.add('2',[3,4])
line_chart.render_to_file('1.svg')
报错:TypeError: object of type 'int' has no len()
更改为:
import pygal
line_chart = pygal.Line()
line_chart.x_labels = ['1','2']
line_chart.add('2',[3,4])
line_chart.render_to_file('1.svg')
后正常
所以问题应该出在了 x轴的label为值为int
检查:
修改xy_map.append([x, sum(y_list) / len(y_list)])为
xy_map.append([str(x), sum(y_list) / len(y_list)])后正常
刚开始学python 如有错误请指正
3q~