使用Python进行数据可视化(三、处理csv文件(二))

简介: 使用Python进行数据可视化(三、处理csv文件(二))

在"使用Python进行数据可视化(三、处理csv文件)"中,我们成功地从csv文件中获取了最高气温的信息,并且绘制了一个直观的折线图。接下来,我们还可以添加一些东西,使其显示更多的信息。

1.显示日期、时间信息

模板 datetime

datetime.datetime

在Python的官方文档中search datetime可以找到关于datetime的使用说明。

class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

......

我们要用到的是:

strptime()

classmethod datetime.strptime(date_string, format)¶

Return a datetime corresponding to date_string, parsed according to format. This is equivalent to datetime(*(time.strptime(date_string, format)[0:6])). ValueError is raised if the date_string and format can’t be parsed by time.strptime() or if it returns a value which isn’t a time tuple. For a complete list of formatting directives, see strftime() and strptime() Behavior.


format的参数很多,在官方文档中可以找到。

从文档的介绍中我们可以知道,strptime的功能和用法,我们传入两个参数,第一个为日期的字符串,第二个为格式设置的参数。 而strptime将返回一个相应日期的对象。

举例:

 

 

给图加上日期

#导入csv模块
import csv
#导入datetime
from datetime import datetime
#
from matplotlib import pyplot as plt
 
#指定文件名,然后使用 with open() as 打开
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
        #创建一个阅读器:将f传给csv.reader
        reader = csv.reader(f)
        #使用csv的next函数,将reader传给next,将返回文件的下一行
        header_row = next(reader)
        
      #  for index, column_header in enumerate(header_row):
                #print(index, column_header)
        
        #读取最高气温
        #创建最高气温的列表
        highs =[]
        dates = []
        #遍历reader的余下的所有行(next读取了第一行,reader每次读取后将返回下一行)
        for row in reader:
                 #
                current_date = datetime.strptime(row[0],"%Y-%m-%d")
                dates.append(current_date)
                #将字符串转换成数字
                high = int(row[1])
                highs.append(high)
               
#绘制图形
fig = plt.figure(dpi=128, figsize=(10,6))
plt.plot(dates,highs,c='red')
#设置图形的格式
plt.title("Daily high temperature, July 2014", 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()
#导入datetime
from datetime import datetime
#
from matplotlib import pyplot as plt

#指定文件名,然后使用 with open() as 打开
filename = 'sitka_weather_07-2014.csv'
with open(filename) as f:
        #创建一个阅读器:将f传给csv.reader
        reader = csv.reader(f)
        #使用csv的next函数,将reader传给next,将返回文件的下一行
        header_row = next(reader)
        
      #  for index, column_header in enumerate(header_row):
                #print(index, column_header)
        
        #读取最高气温
        #创建最高气温的列表
        highs =[]
        dates = []
        #遍历reader的余下的所有行(next读取了第一行,reader每次读取后将返回下一行)
        for row in reader:
                 #
                current_date = datetime.strptime(row[0],"%Y-%m-%d")
                dates.append(current_date)
                #将字符串转换成数字
                high = int(row[1])
                highs.append(high)
               
#绘制图形
fig = plt.figure(dpi=128, figsize=(10,6))
plt.plot(dates,highs,c='red')
#设置图形的格式
plt.title("Daily high temperature, July 2014", 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()

2.更多的信息-将数据扩大到2014年


要将分析的范围扩大到2014年我们只需得到2014年的csv文件,然后同样的方法,就可以得到2014年的最高气温折线图。

将 filename 改为'sitka_weather_2014.csv'

同时修改标题

plt.title("Daily high temperature,  2014", fontsize=24)

即可。

 

3.更多的信息,加上最低气温

和最高气温的方法类似,我们可以读取最低气温,并且把它和最高气温绘制在同一张图上。

    lows= []

    low = int(row[3])

    lows.append(low)

   plt.plot(dates,lows,c= 'blue')  #更改颜色为蓝色,便于区分

添加最低气温后的图表显示如下:


4.更好地显示图表--给图表区域上色

只需更改三处代码 (alpha是透明度),fill_between()填充两条折现之间的区域.

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

plt.plot(dates,lows,c= 'blue',alpha=0.5)

plt.fill_between(dates, highs, lows,facecolor='blue', alpha=0.1)

结果如下:

 

5.错误检查

csv文件中有时会出现一些意料之外的东西,有时会导致错误。

用try,except,else结构来避免错误。

举例:

我试图用同样的方法分析death_valley_2014.csv时,出现了错误。

上面提示我,在30行,执行语句 high=int(row[1])时出现错误,错误类型为ValueError,提示无法将''转化成int。

于是用 try ,except,else结构来避免这种ValueError.

我们将可能出错的部分放在try的内部

except ValueError :在出错时打印一条信息,

else:来执行正常的时候的操作。

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

结果如下:

 

 

可以看出,不仅成功地绘制出了折线图,而且打印出了出现错误时的日期。

 

最后,最终的完整代码:

#导入csv模块
import csv
#导入datetime
from datetime import datetime
#
from matplotlib import pyplot as plt
 
#指定文件名,然后使用 with open() as 打开
filename = 'death_valley_2014.csv'
with open(filename) as f:
        #创建一个阅读器:将f传给csv.reader
        reader = csv.reader(f)
        #使用csv的next函数,将reader传给next,将返回文件的下一行
        header_row = next(reader)
        
      #  for index, column_header in enumerate(header_row):
                #print(index, column_header)
        
        #读取最高气温
        #创建最高气温的列表
        highs =[]
        lows= []
        dates = []
        #遍历reader的余下的所有行(next读取了第一行,reader每次读取后将返回下一行)
        for row in reader:
                try:
                        current_date = datetime.strptime(row[0],"%Y-%m-%d")
                        high = int(row[1])
                        low = int(row[3])
                except ValueError:
                        print(current_date, 'missing data')
                else:
                        dates.append(current_date)
                        highs.append(high)
                        lows.append(low)
               
#绘制图形
fig = plt.figure(dpi=128, figsize=(10,6))
plt.plot(dates,highs,c='red',alpha=0.5)
plt.plot(dates,lows,c= 'blue',alpha=0.5)
plt.fill_between(dates, highs, lows,facecolor='blue', alpha=0.1)
#设置图形的格式
plt.title("Daily high and low temperature,  2014", 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()


相关文章
|
4天前
|
移动开发 Unix Linux
Python 遍历文件每一行判断是否只有一个换行符详解
**Python 检查文件每行换行符:** 文章探讨了在Python中验证文件每行是否仅含一个换行符的需求。通过提供代码示例,展示了如何打开文件,遍历行,判断行尾的换行情况。基础实现检查`\n`,扩展版考虑了`\r\n`,并可选地将结果保存至新文件。这些功能有助于确保数据格式规范。
16 0
|
4天前
|
Python Windows
在 Windows 平台下打包 Python 多进程代码为 exe 文件的问题及解决方案
在使用 Python 进行多进程编程时,在 Windows 平台下可能会出现将代码打包为 exe 文件后无法正常运行的问题。这个问题主要是由于在 Windows 下创建新的进程需要复制父进程的内存空间,而 Python 多进程机制需要先完成父进程的初始化阶段后才能启动子进程,所以在这个过程中可能会出现错误。此外,由于没有显式导入 Python 解释器,也会导致 Python 解释器无法正常工作。为了解决这个问题,我们可以使用函数。
13 5
|
4天前
|
API Python
Python库`openpyxl`是一个用于读取和写入Excel 2010 xlsx/xlsm/xltx/xltm文件的库。
【6月更文挑战第19天】`openpyxl`是Python处理xlsx文件的库,支持读写Excel 2010格式。使用`pip install openpyxl`安装。基本操作包括加载文件、读写单元格、操作行和列。例如,加载Excel后,可以读取单元格`A1`的值,或将“Hello, World!”写入`A1`。还可修改单元格内容,如加1后保存到新文件。更多功能,如样式和公式,见官方文档[1]。 [1]: <https://openpyxl.readthedocs.io/en/stable/>
23 1
|
5天前
|
定位技术 索引 Python
Python GDAL缩放栅格文件各波段数值
本文介绍基于Python中的gdal模块,批量读取大量多波段遥感影像文件,分别对各波段数据加以数值处理,并将所得处理后数据保存为新的遥感影像文件的方法。 首先,看一下本文的具体需求。我们现有一个文件夹,其中含有大量.tif格式的遥感影像文件;其中,这些遥感影像文件均含有4个波段,每1个波段都表示其各自的反射率数值。而对于这些遥感影像文件,有的文件其各波段数值已经处于0至1的区间内(也就是反射率数据的正常数值区间),而有的文件其各波段数值则是还没有乘上缩放系数的(在本文中,缩放系数是0.0001)。
|
2天前
|
数据可视化 数据挖掘 API
Python数据可视化基础:使用Matplotlib绘制图表
Python的Matplotlib是数据可视化的首选库,它提供静态、动态和交互式图表。要开始,先通过`pip install matplotlib`安装。绘制基本折线图涉及导入`pyplot`,设定数据,然后用`plot()`函数画图,如: ```markdown import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] plt.plot(x, y, 'o') plt.show() ``` 自定义图表包括更改线条样式、颜色等,例如: ```markdown
|
2天前
|
Linux 数据处理 文件存储
Python文件自动化处理(一)
`os` 模块是 Python 中用于操作系统交互的核心模块,支持文件和目录的创建、移动、复制等操作,以及处理文件路径和名称。它还提供了 `os.walk()` 函数来遍历目录树,查找文件。字符串方法如 `startswith()` 和 `endswith()` 用于过滤文件名。`glob` 模块则支持使用通配符 (`*`, `?`, `[seq]`) 查找匹配的文件。
|
2天前
|
Python
Python文件自动化处理(二)
使用Python自动化处理Excel涉及`openpyxl`库,包括打开和读取表格数据:`load_workbook()`、获取工作表、获取尺寸;读取单元格数据:`sheet['A1']`、`cell.value`;以及写入内容:`sheet['A1']='hello,Python'`、`cell.value='hello,Python'`、`sheet.append()`和插入行/列。此外,`python-docx`模块用于Word处理,支持创建、修改文档,添加标题、段落、文字、图片和表格,并能设置样式和格式。
|
5天前
|
XML 数据采集 前端开发
Python第二章(HTMl文件,CSS语言与第三方库Beautiful Soup)
Python第二章(HTMl文件,CSS语言与第三方库Beautiful Soup)
|
1月前
|
存储 数据处理 Python
Python中读写CSV文件的深入探讨
Python中读写CSV文件的深入探讨
27 0