2020-10-05 Python编程从入门到实践 第16章 下载数据 动手试一试 16-2 比较锡特卡和死亡谷的气温 习题练习

该博客通过读取并解析CSV文件中的天气数据,对比展示了2014年美国死亡谷和锡特卡两地的气温变化。使用Python的matplotlib库创建了图表,显示了两个城市的每日最高温和最低温度,以随机颜色区分。代码实现了数据读取、转换以及图形绘制功能,有助于理解不同地理位置的气候差异。
摘要由CSDN通过智能技术生成

你还可以尝试在一个图表呈现这两个数据集

 

#compare_DeathValley_and_Sitka_weather.py
#__author__ = 'Liu Shao Ji'
#encoding=utf-8
import csv
from datetime import datetime
from matplotlib.pyplot import MultipleLocator
import matplotlib.pyplot as plt
from C16.try_page_324.try_16_2_2.read_data import read_excel_temp
from C16.try_page_324.try_16_2_2.draw_map import data_draw_map
file_name_1= "death_valley_2014.csv"
file_name_2= "sitka_weather_2014.csv"

DeathValley_Data=read_excel_temp(file_name_1)
DeathValley_weather_Data=DeathValley_Data.get_dates_high_low()

Sitka_Data=read_excel_temp(file_name_2)
Sitka_weather_Data=Sitka_Data.get_dates_high_low()

# print("死亡谷")
#
# print(DeathValley_weather_Data[0])#日期
# print(DeathValley_weather_Data[1])#最高温度
# print(DeathValley_weather_Data[2])#最低温度
# print(DeathValley_weather_Data[3])#表头
#
# print("锡特卡")
#
# print(Sitka_weather_Data[0])#日期
# print(Sitka_weather_Data[1])#最高温度
# print(Sitka_weather_Data[2])#最低温度
# print(Sitka_weather_Data[3])#表头

obj_list=[]
obj_list.append(DeathValley_weather_Data)
obj_list.append(Sitka_weather_Data)
print("包含两个城市天气的数据放在obj_list中\n")
print(obj_list)
print(obj_list[0])
print(obj_list[1])
# def __init__(self,header_row,dates,highs,lows,title):
# draw_map=data_draw_map(DeathValley_weather_Data[3],
#                        DeathValley_weather_Data[0],
#                        DeathValley_weather_Data[1],
#                        DeathValley_weather_Data[2],
#                        "Compare DethValley and Sitka Weather")
# draw_map.draw_map()
print("尝试解释obj_list:\n")
draw_map=data_draw_map(obj_list,DeathValley_weather_Data[3],"two city weather compare")
# draw_map.circle_list()
draw_map.draw_map()
#read_data.py
#__author__ = 'Liu Shao Ji'
#encoding=utf-8
import csv
from datetime import datetime
#用于设置y轴的范围
from matplotlib.pyplot import MultipleLocator
import matplotlib.pyplot as plt

class read_excel_temp():
    def __init__(self,file_name):
        self.file_name=file_name
    def get_dates_high_low(self):
        filename=self.file_name
        with open(filename) as f:
            reader= csv.reader(f)
            """虽然灰色看似没有调用,header_row=next(reader)这行不能注释掉"""
            header_row=next(reader)
            '''两个列表,其中一个放什么呢?'''
            dates,highs,lows=[],[],[]
            for row in reader:
                try:
                    current_date=datetime.strptime(row[0],"%Y-%m-%d")
                    high=int(row[1])
                    low=int(row[3])
                    #华氏转摄氏
                    high_c=(float(row[1])-32)/1.8
                    low_c=(float(row[3])-32)/1.8

                except ValueError:
                    print(current_date,'missing data')
                else:
                    dates.append(current_date)
                    highs.append(high_c)
                    lows.append(low_c)
            return(dates,highs,lows,header_row)
file_name= "death_valley_2014.csv"
sample=read_excel_temp(file_name)
dates_and_highs_and_lows=sample.get_dates_high_low()
print(dates_and_highs_and_lows[0])#日期
print(dates_and_highs_and_lows[1])#最高温度
print(dates_and_highs_and_lows[2])#最低温度
print(dates_and_highs_and_lows[3])#表头

#draw_map.py

#__author__ = 'Liu Shao Ji'
#encoding=utf-8
import csv
from datetime import datetime
#用于设置y轴的范围
import random
from matplotlib.pyplot import MultipleLocator
import matplotlib.pyplot as plt
class data_draw_map():
    #接受一个列表
    # def __init__(self,header_row,dates,highs,lows,title):
    #     self.header_row=header_row
    #     self.dates=dates
    #     self.highs=highs
    #     self.lows=lows
    #     self.title=title
    #     # print(Sitka_weather_Data[0])#日期
    #     # print(Sitka_weather_Data[1])#最高温度
    #     # print(Sitka_weather_Data[2])#最低温度
    #     # print(Sitka_weather_Data[3])#表头
    def __init__(self,data_list,header_row,title):
        self.data_list=data_list
        self.header_row=header_row
        self.title=title
    # def circle_list(self):
    #     objs=self.list
    #     for o in objs:
    #         dates=o[0]
    #         highs=o[1]
    #         lows=o[2]
    #         header_row=o[3]
    #         print(dates)
    #         print(highs)
    #         print(lows)
    #         print(header_row)

    def random_color(self):
        list_number=list(range(0,101))
        a=random.choice(list_number)
        b=a/100
        return b



    def draw_map(self):
        for index,column_header in enumerate(self.header_row):
            print(index,column_header)
            """根据数据绘制气温图表"""
            fig = plt.figure(dpi=128,figsize=(10,6))
            '''321'''


            """生成随机颜色"""
            print("死亡谷日期:"+str(self.data_list[0][0]))
            print("死亡谷高温:"+str(self.data_list[0][1]))
            print("死亡谷低温:"+str(self.data_list[0][2]))

            plt.plot(self.data_list[0][0],self.data_list[0][1],c=(1,self.random_color(),self.random_color()),alpha=0.5)
            plt.plot(self.data_list[0][0],self.data_list[0][2],c=(1,self.random_color(),self.random_color()),alpha=0.5)
            plt.plot(self.data_list[1][0],self.data_list[1][1],c=(self.random_color(),1,self.random_color()),alpha=0.5)
            plt.plot(self.data_list[1][0],self.data_list[1][2],c=(self.random_color(),1,self.random_color()),alpha=0.5)




            plt.fill_between(self.data_list[0][0],self.data_list[0][1],self.data_list[0][2],facecolor=(1,self.random_color(),self.random_color()),alpha=0.3)
            plt.fill_between(self.data_list[1][0],self.data_list[1][1],self.data_list[1][2],facecolor=(self.random_color(),1,self.random_color()),alpha=0.3)
            # title="Daily high temperatures,-2014\nDeath Valley,CA"
            plt.title(self.title,fontsize=24)
            plt.xlabel('',fontsize=16)
            fig.autofmt_xdate()
            plt.ylabel("Temperature(C)",fontsize=16)
            plt.tick_params(axis='both',which='major',labelsize=10)
            #y轴的刻度
            y_major_locator=MultipleLocator(5)
            ax=plt.gca()
            ax.yaxis.set_major_locator(y_major_locator)
            plt.ylim(-10,50)
            plt.show()


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值