• Python数据可视化之交易收盘与天气变化走势图


    下面的案例是绘出交易收盘走势图

    简单说明:整体代码分为5个函数,最后给出了最后两个函数运行的效果图。前面每个函数都为下面的函数做准备。

    函数btc_close_2017()、btc_close_2017_01()、btc_close_2017_02()函数为了显示数据

    函数btc_close_2017_03()、btc_close_2017_04()可视化数据

    绘图用到的函数以及参数说明未单独列出都在程序里注释说明。

    整体代码如下:

      1 #交易收盘走势图:JSON格式
      2 from __future__ import (absolute_import,division,print_function,unicode_literals)
      3 import requests
      4 
      5 def btc_close_2017():
      6     #实现兼容python 2.x和3.x的版本,要用到urlopen函数
      7     try:
      8         from urllib2 import urlopen
      9     except ImportError:
     10         from urllib.request import urlopen
     11 
     12     导入json模块
     13     import json
     14 
     15     json_url = "https://raw.githubusercontent.com/muxuezi/btc/master/btc_close_2017.json"
     16     #调用requests.get()方法向github服务器发送请求,返回结果存储在req中
     17     req = requests.get(json_url)
     18     # 将数据写入文件
     19     with open('btc_close_2017_request.json','w') as f:
     20         #req.text属性可以直接读取文件数据,返回格式为字符串
     21         f.write(req.text)
     22     #直接调用req.json就可将btc_close_2017.json文件转换成python列表file_request
     23     file_request = req.json
     24     """
     25     response = urlopen(json_url)
     26     req = response.read()
     27 
     28     with open("btc_close_2017_urllib.json",'wb') as f:
     29         f.write(req)
     30     file_urllib = json.loads(req)
     31     print(file_urllib)
     32     """
     33     print(req.text)
     34 
     35 import json
     36 
     37 def btc_close_2017_01():
     38     filename = "btc_close_2017.json"
     39     with open(filename) as f:
     40         btc_data = json.load(f)
     41     for btc_dict in btc_data:
     42         date = btc_dict['date']
     43         month = btc_dict['month']
     44         week = btc_dict['week']
     45         weekday = btc_dict['weekday']
     46         close = btc_dict['close']
     47         print ("{} is month {} week{},{},the close price is {}RMB".format(date,month,week,weekday,close))
     48 
     49 # 将字符转化为数字
     50 def btc_close_2017_02():
     51     filename = "btc_close_2017.json"
     52     with open(filename) as f:
     53         btc_data = json.load(f)
     54     for btc_dict in btc_data:
     55         date = btc_dict['date']
     56         month = int(btc_dict['month'])
     57         week = int(btc_dict['week'])
     58         weekday = btc_dict['weekday']
     59         close = int(float(btc_dict['close']))
     60         print ("{} is month {} week{},{},the close price is {}RMB".format(date,month,week,weekday,close))
     61 
     62 import pygal
     63 # 绘制收盘价折线图
     64 def btc_close_2017_03():
     65     filename = "btc_close_2017.json"
     66     with open(filename) as f:
     67         btc_data = json.load(f)
     68     dates = []
     69     month = []
     70     week = []
     71     weekday = []
     72     close = []
     73     for btc_dict in btc_data:
     74         dates.append(btc_dict['date'])
     75         month.append(int(btc_dict['month']))
     76         week.append(int(btc_dict['week']))
     77         weekday.append(btc_dict['weekday'])
     78         close.append(int(float(btc_dict['close'])))
     79 
     80     line_chart = pygal.Line(x_label_rotation=20,show_minor_x_labels=False)
     81     line_chart.title = "收盘价(¥)"
     82     line_chart.x_labels = dates
     83     N = 20
     84     line_chart.x_labels_major = dates[::N]
     85     line_chart.add("收盘价",close)
     86     line_chart.render_to_file('收盘价折线图.svg')
     87 
     88 
     89 import math
     90 #导入python标准库中模块itertools的函数groupby
     91 from itertools import groupby
     92 #计算收盘价均值
     93 def draw_line(x_data,y_data,title,y_legend):
     94     xy_map = []
     95     #将x轴,y轴数据合并排序再用groupby分组,分组之后求出均值
     96     for x,y in groupby(sorted(zip(x_data,y_data)),key = lambda _:_[0]):
     97         y_list = [v for _,v in y]
     98         xy_map.append([x,sum(y_list)/len(y_list)])
     99     #将xy_map中x轴,y轴数据分离
    100     x_unique,y_mean = [*zip(*xy_map)]
    101     #实例化折线图对象并画图
    102     line_chart = pygal.Line()
    103     line_chart.title = title
    104     line_chart.x_labels = x_unique
    105     line_chart.add(y_legend,y_mean)
    106     line_chart.render_to_file(title+".svg")
    107     return line_chart
    108 
    109 def btc_close_2017_04():
    110     filename = "btc_close_2017.json"
    111     with open(filename) as f:
    112         btc_data = json.load(f)
    113     dates = []
    114     month = []
    115     week = []
    116     weekday = []
    117     close = []
    118     for btc_dict in btc_data:
    119         dates.append(btc_dict['date'])
    120         month.append(int(btc_dict['month']))
    121         week.append(int(btc_dict['week']))
    122         weekday.append(btc_dict['weekday'])
    123         close.append(int(float(btc_dict['close'])))
    124 
    125     #x轴日期标签旋转20度,不用显示x轴所有标签
    126     line_chart = pygal.Line(x_label_rotation=20,show_minor_x_labels=False)
    127     line_chart.title = "收盘价对数变换(¥)"
    128     line_chart.x_labels = dates
    129     #x轴每隔20天显示一次
    130     N = 20
    131     line_chart.x_labels_major = dates[::N]
    132     #利用对数变换剔除非线性趋势之后,整体上涨更接近线性增长
    133     close_log = [math.log10(_) for _ in close]
    134     line_chart.add("log收盘价",close_log)
    135     line_chart.render_to_file('收盘价对数变换折线图.svg')
    136 
    137     # 收盘价月日均图
    138     idx_month = dates.index('2017-12-01')
    139     line_chart_month = draw_line(month[:idx_month],close[:idx_month],'收盘价月日均图','月日均值')
    140 
    141 
    142 btc_close_2017_04()
    143 """
    144 btc_close_2017_03()
    145 btc_close_2017_02()
    146 btc_close_2017_01()
    147 """

    收盘价折线图如下:

    收盘价对数变换折线图如下:

    收盘价月日均图如下:

    天气变化折线图程序如下(程序所用函数以及参数含义在注释中已说明):

     1 import csv
     2 from matplotlib import pyplot as plt
     3 from datetime import datetime
     4 
     5 # filename = 'sitka_weather_07-2014.csv'
     6 #要读取的文件
     7 filename = 'sitka_weather_2014.csv'
     8 
     9 #打开文件并将文件结果对象存储到f中
    10 with open(filename) as f:
    11     #创建一个与该文件相关联的阅读器(reader)对象,reader处理文件中以逗号分隔每一行的数据
    12     reader = csv.reader(f)
    13     #模块csv包含函数next(),将阅读器对象传递给它将返回文件的下一行
    14     headr_row = next(reader)
    15 
    16     dates,highs,lows = [],[],[]
    17     for row in reader:
    18         #datetime.strptime()设置时间日期
    19         current_date = datetime.strptime(row[0],"%Y-%m-%d")
    20         dates.append(current_date)
    21 
    22         high = int(row[1])
    23         highs.append(high)
    24 
    25         low = int(row[3])
    26         lows.append(low)
    27 
    28     # 数据可视化
    29     fig = plt.figure(dpi=128,figsize=(10,6))
    30     #红色显示最高气温,蓝色显示最低气温
    31     plt.plot(dates,highs,c='red')
    32     plt.plot(dates,lows,c = 'blue')
    33     #向fill_between()函数传递一个x值:dates 两个y值:highs,lows 中间填充色:blue 透明度:0.5
    34     plt.fill_between(dates,highs,lows,facecolor = 'blue',alpha=0.5)
    35 
    36     #设置图形的格式
    37     plt.title("Daily hight temperatures,July 2014",fontsize=10)
    38     plt.xlabel('',fontsize=5)
    39     #来绘制斜的日期标签
    40     fig.autofmt_xdate()
    41     plt.ylabel("Temperature(F)",fontsize = 10)
    42     plt.tick_params(axis='both',which='major',labelsize = 10)
    43     plt.show()

    效果图如下:

  • 相关阅读:
    wstngfw中配置snort
    ROUTE: route addition failed
    putty和psftp命令行参数
    a2 Bluebottle OS
    Project Oberon
    【批处理学习笔记】第二十五课:间接传递
    【批处理学习笔记】第二十四课:直接传递
    Java异常抛出及try,catch应用实例
    【Python学习笔记之二】浅谈Python的yield用法
    【批处理学习笔记】第二十三课:用户变量和变量引用
  • 原文地址:https://www.cnblogs.com/IamJiangXiaoKun/p/9455228.html
Copyright © 2020-2023  润新知