下载数据(matplotlib可视化16章-1)

 


1、从CSV文件中提取数据

复制代码
import csv

import matplotlib.pyplot as plt

filename = 'sitka_weather_07-2014.csv'
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)

    #提取最高气温
    highs = []
    for row in reader:
        high = int(row[1])
        highs.append(high)
    print(highs)


    fig = plt.figure(dpi=128,figsize=(10,6))
    plt.plot(highs, c='red')

    plt.title("Daily high temperatures, July 2014", fontsize=24)
    plt.xlabel("Date",fontsize=16)
    plt.ylabel("T",fontsize=16)
    plt.tick_params(axis="both",which='major',labelsize=16)
    plt.show()
复制代码

 

2、datetime模块

 

复制代码
import csv
import matplotlib.pyplot as plt
from datetime import datetime

filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
    reader = csv.reader(f)
    header_row = next(reader)

    #提取最高气温和日期
    highs = []
    dates = []
    for row in reader:
        high = int(row[1])
        highs.append(high)
        date =datetime.strptime(row[0], "%Y-%m-%d")
        dates.append(date)
    # print(dates)

    fig = plt.figure(dpi=128,figsize=(10,6))
    plt.plot(dates,highs, c='red')

    plt.title("Daily high temperatures, July 2014", fontsize=24)
    plt.xlabel(" ",fontsize=16)
    fig.autofmt_xdate()
    plt.ylabel("T",fontsize=16)
    plt.tick_params(axis="both",which='major',labelsize=16)
    plt.show()
复制代码

 

 

 

 

 

 3、错误处理

当文件中缺少一些数据时,使用异常处理来解决问题。

复制代码
import csv
from datetime import datetime

import matplotlib.pyplot as plt

filename='death_valley_2014.csv'

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

    highs = []
    lows =[]
    dates = []

    for row in reader:
        try:
            date = datetime.strptime(row[0],"%Y-%m-%d")
            high = int(row[1])
            low = int(row[3])
        except ValueError:
            print(date, 'missing data')
        else:
            highs.append(high)
            lows.append(low)
            dates.append(date)

    plt.plot(dates,highs,c='red',alpha=0.5)
    plt.plot(dates,lows,c='blue',alpha=0.5)
    plt.fill_between(dates,highs,lows,alpha=0.2)
    plt.title("Daily high and low temperatures")
    

    plt.show()
复制代码

 

 

 

posted @   水牛打老鼠  阅读(100)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css
点击右上角即可分享
微信分享提示