利用python的第三方包Pygal制作简单的折线图。

申明:本文仅供学习交流使用。源码大部分来自《python编程从入门到实践》;如有侵权,请联系我删除。

  1 #!usr/bin/env python3
2 # -*-coding=utf-8 -*-
3 '''
4 制作一个简单的交易走势图。源码大部分来自<python编程从入门到实践>
5 过程分析:
6 1,从网站下载数据并存储到本地,两种方法:
7 a,urlopen
8 b,requests
9 2,读取本地数据,利用pygal制作交易走势图
10 '''
11 #正文开始
12 from __future__ import (absolute_import, division, print_function, unicode_literals)
13 try:
14 from urllib2 import urlopen
15 except ImportError:
16 from urllib.request import urlopen
17 import json
18 import requests
19 import pygal
20 from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS
21
22 #第一种方法利用urlopen提取网络上存储的数据
23 #定义要提取数据的url
24 URL = "https://www.xxx.com/btc_close_2017.json"
25 read_url = urlopen(URL) #读取URL
26 read_response = read_url.read() #读取返回的数据
27
28 #开始存储数据到本地, 以'wb'形式(二进制)
29 with open('btc_close_2017_urllib.json', 'wb') as file_object:
30 file_object.write(read_response) #将读取到的数据写入到文件
31
32 file_urllib = json.loads(read_response)
33 print(file_urllib)
34
35 #第二种方法利用requests提取网络上存储的数据
36 #定义要提取数据的URL
37 URL = "https://www.xxx.com/btc_close_2017.json"
38 response = requests.get(URL) #利用requests读取URL并获取数据
39
40 #开始存储数据到本地文件;
41 with open('btc_close_2017_requests.json', 'w') as file_object:
42 file_object.write(response.text) #写入数据到本地文件,要以str格式写入
43
44 file_requests = response.json()
45 print(file_requests)
46
47 print("-----------------------I am delimiter-----------------")
48 #打印一下两种方法是不是获取到相同的数据
49 print(file_urllib == file_requests) #True
50
51 #开始读取相关数据
52 filename = 'btc_close_2017.json'; #加载文件
53
54 #以读的方式打开文件
55 with open(filename) as file_object:
56 btc_data = json.load(file_object) #将读取到的数据加载为json格式
57
58 print(btc_data) #打印是否符合预期
59
60 #打印每一天的信息,并将字符串转换成数值型的:
61 for btc_dict in btc_data:
62 date = btc_dict['date']
63 month = int(btc_dict['month'])
64 week = int(btc_dict['week'])
65 weekday = btc_dict['weekday']
66 close_price = int(float(btc_dict['close'])) #先将字符串转换为浮点型,再将浮点型转换成整型
67 print("{} is month: {}, week: {}, weekday: {}, the close price is: {}".format(date,month,week,weekday,close_price))
68
69
70 #可视化,开始绘制收盘价折线图
71
72 #定义空列表以存储循环得到的项
73 dates, months, weeks, weekdays, close_prices = [], [], [], [], []
74 #循环读取btc_data里的每一项
75 for btc_dict in btc_data:
76 date = btc_dict['date']
77 month = int(btc_dict['month'])
78 week = int(btc_dict['week'])
79 weekday = btc_dict['weekday']
80 close_price = int(float(btc_dict['close'])) #先将字符串转换为浮点型,再将浮点型转换成整型
81
82 #将每一项追加到对应的空列表
83 dates.append(date)
84 months.append(month)
85 weeks.append(week)
86 weekdays.append(weekday)
87 close_prices.append(close_price)
88
89 line_chart = pygal.Line(x_label_rotation=20,show_minor_x_labels=False) #x轴标签顺时针旋转20度,show_minor_x_labels告诉pygal不必显示全部的x轴标签
90 line_chart.title = "Close Price ($)" #标题
91 line_chart.x_title = "Dates" #x轴标题
92 line_chart.y_title = "Price" #y轴标题
93 line_chart.x_labels = dates #x轴标签
94 line_chart.x_labels_major = dates[::20] #让x轴坐标每隔20天显示第一次;
95 line_chart.add("BTC", close_prices) #
96 line_chart.render_to_file('closeprice.svg')
97
98 '''
99 写一些折线图的样式
100 '''
101 my_style = LS("#999888",base_style=LCS)
102 my_config = pygal.Config()
103 my_config.x_label_rotation = 20
104 my_config.show_legend = False
105 my_config.show_minor_x_labels = False
106 my_config.title_font_size = 10
107 my_config.label_font_size = 10
108 my_config.major_label_font_size = 18
109 my_config.truncate_label = 10
110 my_config.show_y_guides = False
111 my_config.width = 1000
112
113 #利用样式可视化
114 line_chart = pygal.Line(my_config,style=my_style)
115 line_chart.title = "BTC close price in 2017"
116 line_chart.x_title = "Dates"
117 line_chart.y_title = "Price"
118 line_chart.x_labels = dates
119 line_chart.x_labels_major = dates[::20]
120 line_chart.add("SPJ",close_prices)
121 line_chart.render_to_file("closeprice1.svg")

Python制作折线图的更多相关文章

  1. JFreeChart在制作折线图

    JFreeChart在制作折线图的时候可以使用两种不同的方式 package Line; import java.awt.Color; import java.awt.Font; import org ...

  2. Microsoft Excel Sheet/表格 制作折线图

    Microsoft Excel Sheet/表格 制作折线图 虽然比较简单,但是仍然需要稍微花一点功夫. 1.制作好表格数据 2.先将数据选定(不包括 横座标的 年月日或其他的刻度 的那一列) 3.插 ...

  3. Python绘制折线图

    一.Python绘制折线图 1.1.Python绘制折线图对应代码如下图所示 import matplotlib.pyplot as pltimport numpy as np from pylab ...

  4. 使用python制作动图

    利用python制作gif图 引言 当写文章时候,多张图片会影响排版,可以考虑制作gif图 准备 pip install imageio 代码 # This is a sample Python sc ...

  5. 利用python进行折线图,直方图和饼图的绘制

    我用10个国家某年的GDP来绘图,数据如下: labels   = ['USA', 'China', 'India', 'Japan', 'Germany', 'Russia', 'Brazil', ...

  6. excel制作折线图太麻烦?试试这些折线图在线生成工具

    折线图是以折线的上升或下降来表示统计数量的增减变化的统计图,叫作折线统计图.用折线的起伏表示数据的增减变化情况,不仅可以表示数量的多少,而且可以反映数据的增减变化情况.并且折线图也是目前最方便的一种统 ...

  7. python matplotlib 折线图

    1.绘制折线图,去上和右边框,显示中文 import numpy as np import matplotlib.pyplot as plt #plt.style.use('default') #pl ...

  8. Vue整合d3.v5.js制作--折线图(line)

    先上效果图(x轴固定为时间轴): 图中出现的悬浮框是鼠标悬停效果 1.环境说明: vue版本:"vue": "^2.5.2" d3版本:"d3&quo ...

  9. python绘折线图

    # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt #X轴,Y轴数据 y = [0.3,0.4,2,5 ...

随机推荐

  1. selenium调用JS实现自动化

    webdriver自带的api使用起来有局限性,比如下拉滚动条文本框输入,以及一些弹出框的操作,使用JS直接操作方便又灵活. 一:示例 from selenium import webdriver f ...

  2. LeetCode周赛#205

    5508. 数的平方等于两数乘积的方法数 #模拟 #哈希表 题目链接 题意 给你两个整数数组nums1 和 nums2 ,请你返回根据以下规则形成的三元组的数目(类型 1 和类型 2 ): 类型 1: ...

  3. java多态2

    1 package pet_2; 2 3 public class Pet { 4 private String name; 5 6 public String getName() { 7 retur ...

  4. java线程与内存的关系

    转载: https://blog.csdn.net/hellozhxy/article/details/91972846

  5. Python命令行参数定义及注意事项

    在命令行中运行python代码是很常见的,下面介绍如何定义命令后面跟的参数. 常规用法 Python代码中主要使用下面几行代码来定义并获取需要在命令行中赋值的参数: import argparse p ...

  6. 简单RTSCamera实现

    using System.Collections; using System.Collections.Generic; using UnityEngine; public class TopCamer ...

  7. 【GDOI2014模拟】JZOJ2020年8月14日提高组 服务器

    [GDOI2014模拟]JZOJ2020年8月14日提高组 服务器 题目 Time and Memory Limits Description 我们需要将一个文件复制到n个服务器上,这些服务器的编号为 ...

  8. C#.NET 强大的LINQ

    LINQ 是 Language INtegrated Query 单词的首字母缩写,翻译过来是语言集成查询.它为查询跨各种数据源和格式的数据提供了一致的模型,所以叫集成查询.由于这种查询并没有制造新的 ...

  9. day6(celery原理与组件)

    1.Celery介绍 1.1 celery应用举例 Celery 是一个 基于python开发的分布式异步消息任务队列,通过它可以轻松的实现任务的异步处理,如果你的业务场景中需要用到异步任务,就可以考 ...

  10. Python使用import导入模块时报ValueError: source code string cannot contain null bytes的解决方案

    老猿在导入一个Python模块时报错: >>> import restartnet.py Traceback (most recent call last): File " ...