python读csv格式文档并用matplotlib绘制图表
Posted endian11
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python读csv格式文档并用matplotlib绘制图表相关的知识,希望对你有一定的参考价值。
-
import csv from matplotlib import 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) # print(header_row) # for index, column_header in enumerate(header_row): # 在同时需要index和value值的时候可以使用 enumerate # # print(index, column_header) dates,hights = [], [] for row in reader: current_date = datetime.strptime(row[0], \'%Y-%m-%d\') dates.append(current_date) hights.append(int(row[1])) print(hights) fig = plt.figure(dpi=128, figsize=(10, 6)) plt.plot(dates, hights, c=\'red\') # 设置图形的格式 plt.title("Dialy high temperatures,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.savefig("temperature.png", bbox_inches=\'tight\') plt.show()
运行结果
- temperature.png
- 现在开始读取全年并展示,代码如下:
import csv from matplotlib import pyplot as plt from datetime import datetime fileName = \'sitka_weather_2014.csv\' with open(fileName) as f: reader = csv.reader(f) header_row = next(reader) dates,hights, lows = [], [], [] for row in reader: current_date = datetime.strptime(row[0], \'%Y-%m-%d\') dates.append(current_date) hights.append(int(row[1])) lows.append(int(row[3])) fig = plt.figure(dpi=128, figsize=(10, 6)) plt.plot(dates, hights, c=\'red\', alpha=0.5) plt.plot(dates, lows, c=\'blue\', alpha=0.5) plt.fill_between(dates, hights, lows, facecolor=\'blue\', alpha=0.1) # 设置图形的格式 plt.title("Dialy high temperatures, 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.savefig("temperature.png", bbox_inches=\'tight\') plt.show()
运行效果:
以上是关于python读csv格式文档并用matplotlib绘制图表的主要内容,如果未能解决你的问题,请参考以下文章
Python Dataframe之excelcsvpicklefeatherparquetjayhdf5 文件存储格式==》存读效率对比
Python Dataframe之excelcsvpicklefeatherparquetjayhdf5 文件存储格式==》存读效率对比