【Python从入门到实践】之 数据可视化

编程入门 行业动态 更新时间:2024-10-26 06:34:49

【Python从<a href=https://www.elefans.com/category/jswz/34/1770026.html style=入门到实践】之 数据可视化"/>

【Python从入门到实践】之 数据可视化

Windows系统首先要安装Visual Studio

绘制简单的折线图

首先安装matplotlib库,Matplotlib 可以绘制多种形式的图形包括普通的线图,直方图,饼图,散点图以及误差线图

import matplotlib.pyplot as plt
squares = [1, 4, 9, 16, 25]
plt.plot(squares)
plt.show()

运行得到的图形:

修改标签文字和线条粗细

tick_params语法:
Axes.tick_params(axis=‘both’, **kwargs)

参数:
axis : {‘x’, ‘y’, ‘both’}
参数axis的值为’x’、 ‘y’、‘both’,分别代表设置X轴、Y轴以及同时设置,默认值为’both’。
labelsize:设置刻度线标签的字体大小,可以是 medium,large,或者具体的字号。
which: 可以设置值’major’、‘minor’、‘both’,分别代表设置主刻度线、副刻度线以及同时设置,默认值为’major’ 。

import matplotlib.pyplot as plt
squares = [1, 4, 9, 16, 25]
plt.plot(squares, linewidth=5)# 设置图表标题,并给坐标轴加上标签
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)# 设置刻度标记的大小
plt.tick_params(axis='both', labelsize=14)plt.show()

运行得到的图形:

校正图形

当向 plot() 函数提供一系列数字时,它默认第一个数据点对应的 x 坐标值是0,为改变这种默认值,我们可以给 plot() 同时提供输入值和输出值。

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.plot(x, y, linewidth=5)# 设置图表标题,并给坐标轴加上标签
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)# 设置刻度标记的大小
plt.tick_params(axis='both', labelsize=14)plt.show()

运行得到的图形:

使用scatter()函数绘制散点图并设置其样式

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
plt.scatter(x, y, s=100)  # s用于设置绘制图形时使用的点的尺寸# 设置图表标题,并给坐标轴加上标签
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)# 设置刻度标记的大小
plt.tick_params(axis='both', labelsize=14, which='major')plt.show()

运行得到的图形:

自定义颜色

在 scatter() 函数中,可以直接指定颜色,例如:c=‘red’,也可以将c设置成元组,其中包含三个0~1之间的小数,分别表示红色、绿色和蓝色的分量,例如:c=(0, 0, 0.8)。

import matplotlib.pyplot as plt
x = list(range(1, 1001))
y = [i**2 for i in x]
plt.scatter(x, y, c='red', s=40)  # s用于设置绘制图形时使用的点的尺寸# 设置图表标题,并给坐标轴加上标签
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)#  设置每个坐标轴的取值范围
plt.axis([0, 1100, 0, 1100000])  # x 和 y 坐标的最大值和最小值plt.show()

运行得到的图形:

颜色映射是一系列颜色,他们从起始颜色渐变到结束颜色。

import matplotlib.pyplot as plt
x = list(range(1, 1001))
y = [i**2 for i in x]
plt.scatter(x, y, c=y, cmap=plt.cm.Reds, s=40)  # s用于设置绘制图形时使用的点的尺寸
'''可以直接指定颜色,也可以将c设置成元组,其中包含三个0~1之间的小数,
分别表示红色、绿色和蓝色的分量,例如:c=(0, 0, 0.8)'''# 设置图表标题,并给坐标轴加上标签
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)# 设置刻度标记的大小
#plt.tick_params(axis='both', labelsize=14, which='major')#  设置每个坐标轴的取值范围
plt.axis([0, 1100, 0, 1100000])  # x 和 y 坐标的最大值和最小值plt.show()

运行得到的图形:

自动保存图表

要让程序自动将图表保存到文件中,可将对 plt.show() 的调用替换为对 plt.savefig() 的调用。
第一个参数指定文件的存储路径及图表文件名;第二个参数指定将图表多余的空白区域裁剪掉。

plt.savefig('D:\\PythonCodes\\1.png', bbox_inches='tight')

找到指定的存储路径,可以看到 图表1.png 。

随机漫步

随机漫步是这样行走得到的路径:每次行走都完全是随机的,没有明确方向,结果是由一系列随机策略决定的。

from random import choice
import matplotlib.pyplot as pltclass RandomWalk:'''一个生成随机漫步数据的类'''def __init__(self, num_points=5000):'''初始化随机漫步的属性'''self.num_points = num_points'''所有的随机漫步都始于(0, 0)'''self.x_values = [0]self.y_values = [0]def fill_walk(self):'''计算随机漫步的所有点'''# 不断漫步,直到列表达到指定的长度while len(self.x_values) < self.num_points:'''决定前进方向以及沿这个方向前进的距离'''x_direction = choice([1, -1])x_distance = choice([0, 1, 2, 3, 4]) # 随机选择0~4之间的整数x_step = x_direction * x_distance # 移动方向乘以移动距离,确定沿x轴移动的距离。y_direction = choice([1, -1])y_distance = choice([0, 1, 2, 3, 4])y_step = y_direction * y_distance# 拒绝原地踏步if x_step == 0 and y_step == 0:continue# 计算下一个点的x和y值next_x = self.x_values[-1] + x_stepnext_y = self.y_values[-1] + y_stepself.x_values.append(next_x)self.y_values.append(next_y)# 创建一个RandomWalk实例,将其中包含的点都绘制出来
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()

运行得到的图表:

使用Pygal模拟掷筛子

首先要安装 pygal 模块,pygal是Python的第三方库,他的主要功能就是将数字转化成图表的形式来呈现,它提供的图表样式有柱状图、折线图、饼状图、雷达图。
柱状图:pygal.Bar()
折线图:pygal.Line()
饼状图:pygal.Pie()
雷达图:pygal.Radar()

from random import randint
import pygalclass Die:'''表示一个骰子的类'''def __init__(self, num_sides=6):'''骰子默认面是6'''self.num_sides = num_sidesdef roll(self):'''返回一个位于1和骰子面之间的随机数'''return randint(1, self.num_sides)  # 起始值1,终止值num_sides之间的任何整数die = Die()# 掷骰子,并将结果存储在一个列表中
results = []
for roll_num in range(1000):result = die.roll()results.append(result)'''print(results)'''# 分析结果,统计每个点数出现的次数
frequencies = []
for value in range(1, die.num_sides + 1):frequency = results.count(value)frequencies.append(frequency)print(frequencies)# 对结果进行可视化 绘制条形图
hist = pygal.Bar()hist.title = "掷骰子1000次的结果"
hist.x_labels = ['1', '2', '3', '4', '5', '6']
hist.x_title = "点数"
hist.y_title = "次数"hist.add('die', frequencies)
hist.render_to_file('die_visual.svg') # 在浏览器中查看

运行得到的图形:

如果同时掷两个骰子,修改原来的代码,创建两个骰子对象。

需将result改变
result = die1.roll() + die2.roll()
将计算次数的代码改成
max_result = die1.num_sides + die2.num_sides
for value in range(2, max_result + 1):frequency = results.count(value)frequencies.append(frequency)

运行得到的图形:

如果要掷两个不同面数的骰子,可以在创建骰子对象时,传入一个参数,例如创建一个10面的骰子:
die2 = Die(10)

CSV文件格式

CSV是逗号分割值文件格式,其文件以纯文本的形式存储表格数据。
分析CSV文件头:

enumerate()函数用于将一个可遍历的数据对象(如列表,元组或字符串)组合成一个索引序列,同时列出数据和数据下标。

import csv
filename = "D:\\PythonCodes\\CSVPractice.CSV"  # CSV文件位置
with open(filename) as f:reader = csv.reader(f)  header_row = next(reader)  # 得到文件的第一行for i, element in enumerate(header_row):print(i, element)

运行得到的结果是:

'''
0 Year
1 Agriculture
2 Architecture
3 Art and Performance
4 Biology
5 Business
6 Communications and Journalism
7 Computer Science
8 Education
9 Engineering
10 English
11 Foreign Languages
12 Health Professions
13 Math and Statistics
14 Physical Sciences
15 Psychology
16 Public Administration
17 Social Sciences and History
'''可以看到得到的是文件的第一行内容

提取并读取数据:
我们来读取第12列的数据 Foreign Languages。

import csv
filename = "D:\\PythonCodes\\CSVPractice.CSV"
with open(filename) as f:reader = csv.reader(f)header_row = next(reader)Foreign_Languages = []for row in reader:Foreign_Language = float(row[11])  # 将得到的列表中的每个字符串转化成float数字形式,便于后续的数据可视化。Foreign_Languages.append(Foreign_Language)print(Foreign_Languages)

运行得到的结果是:

'''
[73.8, 73.9, 74.6, 74.9, 75.3, 75.0, 74.4, 74.3, 74.3, 74.2, 74.1, 73.9, 72.7, 71.8, 72.1, 70.8, 71.2, 72.0, 72.3, 72.4, 71.2, 71.1, 71.0, 70.0, 69.1, 69.6, 69.7, 70.0, 70.1, 70.9, 70.9, 71.2, 70.5, 70.6, 70.8, 69.9, 69.6, 70.2, 70.2, 69.3, 69.0, 69.5]
'''

绘制图表:

figure(figsize=None, dpi=None)
figsize:指定figure的宽和高,单位为英寸
dpi:指定绘图对象的分辨率,即每英寸多少个像素,dpi越大则图形越大

import csv
from matplotlib import pyplot as plt# 从文件中获取Foreign Languages列的数据,即上面的代码要那到这里用# 根据数据绘制图形
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(Foreign_Languages, c='red')# 设置图形的格式
plt.title('Foreign Languages')
plt.xlabel('', fontsize=16)
plt.ylabel('FL', fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)plt.show()

运行得到的图形:

在图表中添加时间:
只需导入 datetime 模块中的 datetime 类,然后调用方法 strptime() 根据指定的格式把一个时间字符串解析为相应日期的对象。

import csv
from matplotlib import pyplot as plt
from datetime import datetime
filename = "D:\\PythonCodes\\CSVPractice.CSV"
with open(filename) as f:reader = csv.reader(f)header_row = next(reader)dates, Foreign_Languages = [], []for row in reader:current_date = datetime.strptime(row[0], "%Y")dates.append(current_date)Foreign_Language = float(row[11])Foreign_Languages.append(Foreign_Language)print(Foreign_Languages)# 根据数据绘制图形
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(dates, Foreign_Languages, c='red')# 设置图形的格式
plt.title('Foreign Languages')
plt.xlabel('', fontsize=16)
fig.autofmt_xdate()  # 调用该函数来绘制斜的日期标签,以防止他们重叠
plt.ylabel('FL', fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)plt.show()

运行得到的图形:

再绘制一个数据系列并给图表区域着色:

plot 函数可添加实参 alpha,用于指定颜色的透明度,alpha 值为0表示完全透明,1(默认设置)表示完全不透明,下面程序将 alpha 的值设置为0.5,可以使红色和绿色的折线颜色看起来更浅。
fill_between() 函数可以接收一个 x 值系列和两个 y 值系列,并填充两个 y 值系列之间的空间。实参 facecolor 指定了填充区域的颜色。

import csv
from matplotlib import pyplot as plt
from datetime import datetime
filename = "D:\\PythonCodes\\CSVPractice.CSV"
with open(filename) as f:reader = csv.reader(f)header_row = next(reader)# print(header_row)dates, Foreign_Languages, Health_Professions = [], [], []for row in reader:'''Foreign_Languages.append(row[11])'''current_date = datetime.strptime(row[0], "%Y")dates.append(current_date)Foreign_Language = float(row[11])Foreign_Languages.append(Foreign_Language)Health_Profession = float(row[12])Health_Professions.append(Health_Profession)print(Foreign_Languages)# 根据数据绘制图形
fig = plt.figure(dpi=128, figsize=(10, 6))
plt.plot(dates, Foreign_Languages, c='red', alpha=0.5)
plt.plot(dates, Health_Professions, c='green', alpha=0.5)
plt.fill_between(dates, Foreign_Languages, Health_Professions, facecolor='blue', alpha=0.1)# 设置图形的格式
plt.title('Foreign Languages and HealthProfessions')
plt.xlabel('', fontsize=16)
fig.autofmt_xdate()  # 调用该函数来绘制斜的日期标签,以防止他们重叠
plt.ylabel('FL', fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)plt.show()

运行得到的图形:

JSON文件格式

JSON(JavaScript Object Notation) 是用来存储简单的数据结构和对象的文件,是一种轻量级的数据交换格式。
提取JSON文件中的数据:

import json# 将数据加载到一个列表中
filename = 'D:\\PythonCodes\\btc_close_2017.json'
with open(filename) as f:btc_data = json.load(f)# 打印每一天的信息
for btc_dict in btc_data:date = btc_dict['date']month = btc_dict['month']week = btc_dict['week']weekday = btc_dict['weekday']close = btc_dict['close']print("{} is month {} week {}, {}, the close price is {}".format(date, month, week, weekday, close))

运行得到的结果是:

2017-01-01 is month 01 week 52, Sunday, the close price is 6928.6492
2017-01-02 is month 01 week 1, Monday, the close price is 7070.2554
2017-01-03 is month 01 week 1, Tuesday, the close price is 7175.1082
.....
2017-12-11 is month 12 week 50, Monday, the close price is 110642.88
2017-12-12 is month 12 week 50, Tuesday, the close price is 113732.6745

将字符串转化为数字值:

import json# 将数据加载到一个列表中
filename = 'D:\\PythonCodes\\btc_close_2017.json'
with open(filename) as f:btc_data = json.load(f)# 打印每一天的信息
for btc_dict in btc_data:date = btc_dict['date']month = int(btc_dict['month'])week = int(btc_dict['week'])weekday = btc_dict['weekday']close = int(float(btc_dict['close']))  # 不能直接将含小数点的字符串转化为int类型,因此要先转化成float类型,再转化成intprint("{} is month {} week {}, {}, the close price is {}".format(date, month, week, weekday, close))

运行得到的结果:

2017-01-01 is month 1 week 52, Sunday, the close price is 6928
2017-01-02 is month 1 week 1, Monday, the close price is 7070
2017-01-03 is month 1 week 1, Tuesday, the close price is 7175
......
2017-12-11 is month 12 week 50, Monday, the close price is 110642
2017-12-12 is month 12 week 50, Tuesday, the close price is 113732

绘制折线图:

import json
import pygal# 将数据加载到一个列表中
filename = 'D:\\PythonCodes\\btc_close_2017.json'
with open(filename) as f:btc_data = json.load(f)# 创建五个列表,分别存储日期和收盘价
dates, months, weeks, weekdays, close = [], [], [], [], []
# 每一天的信息
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'])))# 设置图表样式
line_chart = pygal.Line(x_label_rotation=20, show_minor_x_labels=False)
line_chart.title = '收盘价(¥)'
line_chart.x_labels = dates
N = 20 # x 轴坐标每隔20天显示一次
line_chart.x_labels_major = dates[::N]
line_chart.add('收盘价', close)
line_chart.render_to_file('收盘价折线图(¥).svg')

在创建 Line 实例时,分别设置了 x_label_rotation 和 show_minor_x_labels 作为初始化参数。x_label_rotation 让 x 轴上的日期标签顺时针旋转 20°,show_minor_x_labels=False 告诉图形不用显示所有的 x 轴标签,然后设置 x_labels_major 属性,让 x 轴坐标每隔20天显示一次。

运行得到的 svg 文件在浏览器中打开的图表是:

上面使用的文件是网盘地址,提取码:9tko
我是快斗,欢迎批评指正!

更多推荐

【Python从入门到实践】之 数据可视化

本文发布于:2024-02-24 21:55:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1696793.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:入门   数据   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!