当前位置:   article > 正文

Python 解析CSV文件 使用Matplotlib绘图

Python 解析CSV文件 使用Matplotlib绘图

数据存储在CSV文件中,使用Matplotlib实现数据可视化。

CSV文件:comma-separated values,是在文件中存储一系列以‘,’分隔的值。

例如:"0.0","2016-01-03","1","3","2016","Birmingham","BHM","Birmingham, AL","Alabama","39","46","32","33","4.33"

本文使用的CSV文件是一组天气数据

Matplotlib绘图代码如下:

  1. import csv
  2. import matplotlib.pyplot as plt
  3. plt.rcParams['font.sans-serif']=['SimHei']#为显示中文设置字体
  4. from datetime import datetime
  5. filename = 'data/weather.csv'
  6. with open(filename) as f:
  7. reader = csv.reader(f)
  8. header_row = next(reader)
  9. # for index,info in enumerate(header_row):
  10. # print(index,info)
  11. # 0 Data.Precipitation
  12. # 1 Date.Full
  13. # 2 Date.Month
  14. # 3 Date.Week of
  15. # 4 Date.Year
  16. # 5 Station.City
  17. # 6 Station.Code
  18. # 7 Station.Location
  19. # 8 Station.State
  20. # 9 Data.Temperature.Avg Temp
  21. # 10 Data.Temperature.Max Temp
  22. # 11 Data.Temperature.Min Temp
  23. # 12 Data.Wind.Direction
  24. # 13 Data.Wind.Speed
  25. #从文件中获得特定地点Birmingham信息
  26. Birmingham_highs, Birmingham_lows= [],[]
  27. Birmingham_dates = []
  28. for row in reader:
  29. if row[5] == 'Birmingham':
  30. date = datetime.strptime(row[1], '%Y-%m-%d')
  31. high = int(row[10])
  32. low = int(row[11])
  33. Birmingham_dates.append(date)
  34. Birmingham_highs.append(high)
  35. Birmingham_lows.append(low)
  36. plt.style.use('Solarize_Light2')
  37. fig,ax = plt.subplots(figsize=(10,6))#设置窗口尺寸
  38. ax.plot(Birmingham_dates,Birmingham_highs,linewidth=3,c='red',alpha=0.5)#绘制最高温折线,红色,透明度0.5
  39. ax.plot(Birmingham_dates,Birmingham_lows,linewidth=3,c='blue',alpha=0.5)#绘制最低温折线
  40. ax.fill_between(Birmingham_dates,Birmingham_highs,Birmingham_lows,facecolor='yellow',alpha=0.1)#填充中间区域
  41. ax.set_title('2016年-2017年Birmingham最高最低温度变化曲线',fontsize=24)
  42. ax.set_xlabel('',fontsize=14)
  43. fig.autofmt_xdate()#绘制倾斜的日期标签
  44. ax.set_ylabel('温度(F)',fontsize=14)
  45. ax.tick_params(axis='both',which='major',labelsize=14)
  46. plt.savefig('Birmingham_temperature.png',bbox_inches='tight')#将绘制的图形保存为文件
  47. plt.show()

运行结果如下:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/303413
推荐阅读
相关标签
  

闽ICP备14008679号