绘制每天最高/低温度

绘制每天最高/低温度

数据准备

数据下载地址:

https://www.ituring.com.cn/book/1861

然后找到“随书下载”,下载“《Python编程》源代码文件-更新.zip”,解压,在chapter_16目录下有如下两个文件:

  • sitka_weather_07-2014.csv
  • sitka_weather_2014.csv

这就是我们需要的数据。

代码
import csv

import matplotlib.pyplot as plt
from datetime import datetime

# filename = "sitka_weather_07-2014.csv"  # 32行数据
filename = "sitka_weather_2014.csv"    # 356行数据
highs = []  # 最高气温
lows = []  # 最低气温
dates = [ ]  # 日期

with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

    # 打印表头行
    # print(header_row)

    # 打印表头的每一列
    # for index, column_header in enumerate(header_row):
    #    print(index, column_header)

    for row in reader:
        dates.append(datetime.strptime(row[0], "%Y-%m-%d"))  # 记录日期
        highs.append(int(row[1]))  # 记录每天的最高气温,并且转换为整型
        lows.append(int(row[3]))  # 记录每天的最低气温,并且转换为整型

# 打印每天的最高气温
# print(highs)

# 绘制图形
fig = plt.figure(dpi=128, figsize=(106))
plt.plot(dates, highs, c="red", alpha=0.5)  # 绘制最高气温折线图,用红色表示
# alpha表示透明度,0为完全透明,1(默认值)表示完全不透明
plt.plot(dates, lows, c="blue", alpha=0.5)  # 绘制最低气温折线图,用蓝色表示
plt.fill_between(dates, highs, lows, facecolor="blue", alpha=0.2)
# fill_between接受一个x和两个y值,并填充两个y值之间的空间
# facecolor指定填充的颜色

plt.title("Daily high/low temperature", fontsize=24)
plt.xlabel("", fontsize=16)
fig.autofmt_xdate()  # 这一行是自动优化日期的显示,如果没这一行,日期会重叠,因为放不下那么多,有了这一句,日期会斜着放,而且会根据空间自动选取该展示的日期
plt.ylabel("Temperature(F)", fontsize=16)
plt.tick_params(axis="both", which="major", labelsize=16)

plt.show()

图示见下图。

绘制每天最高/低温度

知识点

csv读取文件

reader = csv.reader(file_obj)

datetime将日期字符串转化为日期对象

date = datetime.strptime(date_string, date_format)

matplotlib绘制图形时,指定图形的透明度

alpha参数,0为完全透明,1(默认值)完全不透明

plt.plot(dates, highs, c="red", alpha=0.5

matplotlib填充两个y值之间的空间

plt.fill_between()

plt.fill_between(dates, highs, lows, facecolor="blue")

matplotlib自动对x轴的日期进行整理

plt.autofmt_xdate()

fig.autofmt_xdate() 


原文始发于微信公众号(Know Why It):绘制每天最高/低温度

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/276235.html

(0)
python学霸的头像python学霸bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!