- JSON 与 CSV(逗号分割的值)
- matplotlib demo https://matplotlib.org/gallery/index.html
# 解析CSV天气数据并使用matplotlib
将数据绘制成折线图
- 数据
- 解析数据与绘图
import csv from matplotlib import pyplot as plt from datetime import datetime def read_data_from_csv(): """ 从CSV文件中读取日期/最高温/最低温数据 :return: """ # file_path = 'data/sitka_weather_07-2014.csv' file_path = 'data/sitka_weather_2014.csv' # file_path = 'data/death_valley_2014.csv' with open(file_path) as csv_file: csv_reader = csv.reader(csv_file) # enumerate(iterable)可用来获取每个元素的索引 for index, item in enumerate(next(csv_reader)): print(index, item) # 日期 dates = [] # 用于保存每天的最高气温 highs = [] # 最低温 lows = [] for row in csv_reader: # 将字符串转换为指定格式的datetime dates.append(datetime.strptime(row[0], '%Y-%m-%d')) # 最最高温数据 highs.append(int(row[1])) # 最低温数据 lows.append(int(row[3])) return [dates, highs, lows] def draw(data): """ 绘图 :param data: 日期与温度 :return: """ plt.figure(dpi=128, figsize=(10, 6)) # 绘制最高温 plt.plot(data[0], data[1], c='red') # 绘制最低温 plt.plot(data[0], data[2], c='blue') # 填充温度之间的区域 plt.fill_between(data[0], data[1], data[2], facecolor='blue', alpha=0.1) plt.show() draw(read_data_from_csv())
- 结果:
日期参数
# 解析股价走势json数据并使用pygal绘制折线图
数据
- 代码
import json import pygal def read_json_data_from_file(file_path: str): """ 读取json文件数据 :param file_path: :return: 解析的字典 """ date = "date" month = "month" week = "week" weekday = "weekday" close = "close" # 打开文件 with open(file_path) as json_file: # 解析为json json_data = json.load(json_file) # 存储数据集 dates, months, weeks, weekdays, closes = [], [], [], [], [] # 遍历json数组 for json_obj in json_data: # 每个json对象都是一个dict,取到json的每个属性值 dates.append(json_obj[date]) months.append(json_obj[month]) weeks.append(json_obj[week]) weekdays.append(json_obj[weekday]) closes.append(float(json_obj[close])) return {"dates": dates, "months": months, "weeks": weeks, "weekdays": weekdays, "closes": closes} def draw(data: dict): """绘图""" line_chart = pygal.Line(x_label_rotation=20, show_minor_x_labels=False) line_chart.title = "收盘价折线图" line_chart.x_labels = data["dates"] # X轴每隔20天显示一次 N = 20 line_chart.x_labels_major = data["dates"][::N] line_chart.add("收盘价", data["closes"]) line_chart.render_to_file('收盘价折线图.svg') json_file_path = "btc/btc_close_2017.json" draw(read_json_data_from_file(json_file_path))
- 结果