【自学】python初学 LESSON 8 <数据可视化——下载数据1>

文章目录

前言

 一、CSV文件格式

1. 分析CSV文件头

2. 分析每个文件头的索引

3.  提取并读取数据

4. 绘制温度图表

 4.1 模块datetime添加日期

4.2 再绘制一个数据系列

二、练习

总结


前言

使用CSV来处理CSV格式存储天气数据,找出两个地区在一段时间内的最高温度和最低温度。然后使用MATPLOTLIB根据下载的数据创建一个图表,展示温度变化。

往期画图文章见链接:

https://blog.csdn.net/mzy20010420/article/details/126047773?spm=1001.2014.3001.5501icon-default.png?t=M666https://blog.csdn.net/mzy20010420/article/details/126047773?spm=1001.2014.3001.5501https://blog.csdn.net/mzy20010420/article/details/126083397?spm=1001.2014.3001.5501icon-default.png?t=M666https://blog.csdn.net/mzy20010420/article/details/126083397?spm=1001.2014.3001.5501


一、CSV文件格式

在文本文件中存储数据,以逗号作为分隔。以下操作均是对某一列进行操作

1. 分析CSV文件头

代码:

import csv

#表格题头(每列代表的含义)
filename = 'C:/Users/Administrator/Desktop/sitka_weather_07-2014.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader) #只调用了一次next(),因此读取文件第一行
    print(header_row)

结果:

['STATION', 'NAME', 'DATE', 'PRCP', 'TAVG', 'TMAX', 'TMIN']

分析:

(1)模块csv包含函数next(),调用它并传入阅读器对象时,它将返回文件的下一行。由于只调用了next()一次,因此得到文件第一行,包含文件头。将返回的数据存储到header_row中,并打印。

(2)reader处理文件中以逗号分隔的第一行数据。

2. 分析每个文件头的索引

想要知道每个文件头在第几列

代码:

import csv

#表格题头(每列代表的含义)
filename = 'C:/Users/Administrator/Desktop/sitka_weather_07-2018_simple.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader) #只调用了一次next(),因此读取文件第一行
    
    for index, colum_header in enumerate(header_row):
        print(index, colum_header)

结果:

0 STATION
1 NAME
2 DATE
3 PRCP
4 TAVG
5 TMAX
6 TMIN

评价:

目前看来该功能意义不大

3. 提取并读取数据

想要读取TMAX这一列的数据

代码:

import csv

#表格题头(每列代表的含义)
filename = 'C:/Users/Administrator/Desktop/sitka_weather_07-2018_simple.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader) #只调用了一次next(),因此读取文件第一行
    
    highs = []
    for row in reader:
        high = int(row[5]) #用int()将字符串转化为数值格式
        highs.append(high)

print(highs)

结果:

[62, 58, 70, 70, 67, 59, 58, 62, 66, 59, 56, 63, 65, 58, 56, 59, 64, 60, 60, 61, 65, 65, 63, 59, 64, 65, 68, 66, 64, 67, 65]

注意:

(1)由于CSV文件中都是字符串,因此在对high进行赋值时,要用int()将字符串转化为数值格式。

(2)row代表2*2矩阵的每一行,每一行的第五个就是TMAX的其中一个值。

4. 绘制温度图表

绘制温度曲线图

代码:

import csv
import matplotlib.pyplot as plt

#表格题头(每列代表的含义)
filename = 'C:/Users/Administrator/Desktop/sitka_weather_07-2018_simple.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader) #只调用了一次next(),因此读取文件第一行
    
    highs = []
    for row in reader:
        high = int(row[5]) #用int()将字符串转化为数值格式
        highs.append(high)

#绘制最高温度曲线
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(highs, c = 'red')

#显示中文字符套餐
from pylab import *
mpl.rcParams['font.sans-serif']=['SimHei']


#设置图形格式
ax.set_title('2018年7月每日最高温度', fontsize = 24)
ax.set_xlabel('', fontsize = 16)
ax.set_ylabel('温度(F)', fontsize = 16)
ax.tick_params(axis = 'both', which = 'major', labelsize = 16)

plt.show()    

结果:

 4.1 模块datetime添加日期

代码:

import csv
import matplotlib.pyplot as plt
from datetime import datetime

#表格题头(每列代表的含义)
filename = 'C:/Users/Administrator/Desktop/sitka_weather_07-2018_simple.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader) #只调用了一次next(),因此读取文件第一行
    
    #获取最高温度和日期
    dates, highs = [], []
    for row in reader:
        current_date = datetime.strptime(row[2], '%Y-%m-%d')
        high = int(row[5]) #用int()将字符串转化为数值格式
        dates.append(current_date)
        highs.append(high)
    

#绘制最高温度曲线
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(dates, highs, c = 'red')

#显示中文字符套餐
from pylab import *
mpl.rcParams['font.sans-serif']=['SimHei']


#设置图形格式
ax.set_title('2018年7月每日最高温度', fontsize = 24)
ax.set_xlabel('', fontsize = 16)
fig.autofmt_xdate() #使日期标签倾斜,不会彼此重叠
ax.set_ylabel('温度(F)', fontsize = 16)
ax.tick_params(axis = 'both', which = 'major', labelsize = 16)

plt.show()    

结果:

 注意:

(1)获取最高温度和时间时一定要在一起,不可分开获取。如下代码会报错,具体原因不清楚。

代码:

 #获取最高温度和日期
    highs = []
    for row in reader:
        
        high = int(row[5]) #用int()将字符串转化为数值格式
        
        highs.append(high)
    
    dates = []
    for row in reader:
        current_date = datetime.strptime(row[2], '%Y-%m-%d')
        dates.append(current_date)

结果:

ValueError: x and y must have same first dimension, but have shapes (0,) and (31,)

(2)在画图时一定要有fig.autofmt_xdate()这一行代码,否则x轴的日期会彼此重叠。如下图:

4.2 再绘制一个数据系列

将最高温度、最低温度绘制在同一张图中。

代码:

# -*- coding: utf-8 -*-
"""
Created on Sat Aug  6 14:42:34 2022

@author: Administrator
"""
import csv
import matplotlib.pyplot as plt
from datetime import datetime

#表格题头(每列代表的含义)
filename = 'C:/Users/Administrator/Desktop/sitka_weather_2018_simple.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader) #只调用了一次next(),因此读取文件第一行
    
    #获取最高温度、最低温度和日期
    dates, highs, lows = [], [], []
    for row in reader:
        current_date = datetime.strptime(row[2], '%Y-%m-%d')
        high = int(row[5]) #用int()将字符串转化为数值格式
        low = int(row[6])
        dates.append(current_date)
        highs.append(high)
        lows.append(low)
    

#绘制最高温度曲线
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(dates, highs, c = 'red')
ax.plot(dates, lows, c = 'blue')

#显示中文字符套餐
from pylab import *
mpl.rcParams['font.sans-serif']=['SimHei']


#设置图形格式
ax.set_title('2018年每日最高、最低温度', fontsize = 24)
ax.set_xlabel('', fontsize = 16)
fig.autofmt_xdate() #使日期标签倾斜,不会彼此重叠
ax.set_ylabel('温度(F)', fontsize = 16)
ax.tick_params(axis = 'both', which = 'major', labelsize = 16)

plt.show()    

结果:

 4.3 中间区域着色

代码:

# -*- coding: utf-8 -*-
"""
Created on Sat Aug  6 14:42:34 2022

@author: Administrator
"""
import csv
import matplotlib.pyplot as plt
from datetime import datetime

#表格题头(每列代表的含义)
filename = 'C:/Users/Administrator/Desktop/sitka_weather_2018_simple.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader) #只调用了一次next(),因此读取文件第一行
    
    #获取最高温度、最低温度和日期
    dates, highs, lows = [], [], []
    for row in reader:
        current_date = datetime.strptime(row[2], '%Y-%m-%d')
        high = int(row[5]) #用int()将字符串转化为数值格式
        low = int(row[6])
        dates.append(current_date)
        highs.append(high)
        lows.append(low)
    

#绘制最高温度曲线
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(dates, highs, c = 'red', alpha = 1)
ax.plot(dates, lows, c = 'blue', alpha = 1)
#着色
ax.fill_between(dates, highs, lows, facecolor = 'purple', alpha = 0.2)

#显示中文字符套餐
from pylab import *
mpl.rcParams['font.sans-serif']=['SimHei']


#设置图形格式
ax.set_title('2018年每日最高、最低温度', fontsize = 24)
ax.set_xlabel('', fontsize = 16)
fig.autofmt_xdate() #使日期标签倾斜,不会彼此重叠
ax.set_ylabel('温度(F)', fontsize = 16)
ax.tick_params(axis = 'both', which = 'major', labelsize = 16)

plt.show()    

结果:

 注意:

(1)使用方法fill_between()进行着色。他接受一个x值系列和两个y值系列,并填充两个y值系列之间的空间。

(2)alpha指定颜色的透明度,0为完全透明,1为完全不透明。

二、练习

 16-1

代码:

import csv
import matplotlib.pyplot as plt
from datetime import datetime

#表格题头(每列代表的含义)
filename = 'C:/Users/Administrator/Desktop/death_valley_2018_simple.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader) #只调用了一次next(),因此读取文件第一行


    
    #注意,以下部分一定要在with内部进行
    dates, prcps = [], []
    for row in reader:
        current_date = datetime.strptime(row[2], '%Y-%m-%d')
        prcp = float(row[3])
        dates.append(current_date)
        prcps.append(prcp)

#绘制降水量曲线
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(dates, prcps, c = 'red')

#显示中文字符套餐
from pylab import *
mpl.rcParams['font.sans-serif']=['SimHei']

#设置图形格式
ax.set_title('降水量', fontsize = 24)
ax.set_xlabel('', fontsize = 16)
fig.autofmt_xdate() #使日期标签倾斜,不会彼此重叠
ax.set_ylabel('mm', fontsize = 16)
ax.tick_params(axis = 'both', which = 'major', labelsize = 16)

plt.show()    

结果:


总结

画图看似简单,对数据类型有严格要求。需要具体实践时不断发现新的问题。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rachel MuZy

你的鼓励是我的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值