Python关于excel和shp的使用在matplotlib


Posted in Python onJanuary 03, 2019

关于excel和shp的使用在matplotlib

  • 使用pandas 对excel进行简单操作
  • 使用cartopy 读取shpfile 展示到matplotlib中
  • 利用shpfile文件中的一些字段进行一些着色处理
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : map02.py
# @Author: huifer
# @Date : 2018/6/28
import folium
import pandas as pd
import requests
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import zipfile
import cartopy.io.shapereader as shaperead
from matplotlib import cm
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
import os
dataurl = "http://image.data.cma.cn/static/doc/A/A.0012.0001/SURF_CHN_MUL_HOR_STATION.xlsx"
shpurl = "http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/10m/cultural/ne_10m_admin_0_countries.zip"
def download_file(url):
  """
  根据url下载文件
  :param url: str
  """
  r = requests.get(url, allow_redirects=True)
  try:
    open(url.split('/')[-1], 'wb').write(r.content)
  except Exception as e:
    print(e)
def degree_conversion_decimal(x):
  """
  度分转换成十进制
  :param x: float
  :return: integer float
  """
  integer = int(x)
  integer = integer + (x - integer) * 1.66666667
  return integer
def unzip(zip_path, out_path):
  """
  解压zip
  :param zip_path:str
  :param out_path: str
  :return:
  """
  zip_ref = zipfile.ZipFile(zip_path, 'r')
  zip_ref.extractall(out_path)
  zip_ref.close()
def get_record(shp, key, value):
  countries = shp.records()
  result = [country for country in countries if country.attributes[key] == value]
  countries = shp.records()
  return result
def read_excel(path):
  data = pd.read_excel(path)
  # print(data.head(10)) # 获取几行
  # print(data.ix[data['省份']=='浙江',:].shape[0]) # 计数工具
  # print(data.sort_values('观测场拔海高度(米)',ascending=False).head(10))# 根据值排序
  # 判断经纬度是什么格式(度分 、 十进制) 判断依据 %0.2f 是否大于60
  # print(data['经度'].apply(lambda x:x-int(x)).sort_values(ascending=False).head()) # 结果判断为度分保存
  # 坐标处理
  data['经度'] = data['经度'].apply(degree_conversion_decimal)
  data['纬度'] = data['纬度'].apply(degree_conversion_decimal)
  ax = plt.axes(projection=ccrs.PlateCarree())
  ax.set_extent([70, 140, 15, 55])
  ax.stock_img()
  ax.scatter(data['经度'], data['纬度'], s=0.3, c='g')
  # shp = shaperead.Reader('ne_10m_admin_0_countries/ne_10m_admin_0_countries.shp')
  # # 抽取函数 州:国家
  # city_list = [country for country in countries if country.attributes['ADMIN'] == 'China']
  # countries = shp.records()
  plt.savefig('test.png')
  plt.show()
def gdp(shp_path):
  """
  GDP 着色图
  :return:
  """
  shp = shaperead.Reader(shp_path)
  cas = get_record(shp, 'SUBREGION', 'Central Asia')
  gdp = [r.attributes['GDP_MD_EST'] for r in cas]
  gdp_min = min(gdp)
  gdp_max = max(gdp)
  ax = plt.axes(projection=ccrs.PlateCarree())
  ax.set_extent([45, 90, 35, 55])
  for r in cas:
    color = cm.Greens((r.attributes['GDP_MD_EST'] - gdp_min) / (gdp_max - gdp_min))
    ax.add_geometries(r.geometry, ccrs.PlateCarree(),
             facecolor=color, edgecolor='black', linewidth=0.5)
    ax.text(r.geometry.centroid.x, r.geometry.centroid.y, r.attributes['ADMIN'],
        horizontalalignment='center',
        verticalalignment='center',
        transform=ccrs.Geodetic())
  ax.set_xticks([45, 55, 65, 75, 85], crs=ccrs.PlateCarree()) # x坐标标注
  ax.set_yticks([35, 45, 55], crs=ccrs.PlateCarree()) # y 坐标标注
  lon_formatter = LongitudeFormatter(zero_direction_label=True)
  lat_formatter = LatitudeFormatter()
  ax.xaxis.set_major_formatter(lon_formatter)
  ax.yaxis.set_major_formatter(lat_formatter)
  plt.title('GDP TEST')
  plt.savefig("gdb.png")
  plt.show()
def run_excel():
  if os.path.exists("SURF_CHN_MUL_HOR_STATION.xlsx"):
    read_excel("SURF_CHN_MUL_HOR_STATION.xlsx")
  else:
    download_file(dataurl)
    read_excel("SURF_CHN_MUL_HOR_STATION.xlsx")
def run_shp():
  if os.path.exists("ne_10m_admin_0_countries"):
    gdp("ne_10m_admin_0_countries/ne_10m_admin_0_countries.shp")
  else:
    download_file(shpurl)
    unzip('ne_10m_admin_0_countries.zip', "ne_10m_admin_0_countries")
    gdp("ne_10m_admin_0_countries/ne_10m_admin_0_countries.shp")
if __name__ == '__main__':
  # download_file(dataurl)
  # download_file(shpurl)
  # cas = get_record('SUBREGION', 'Central Asia')
  # print([r.attributes['ADMIN'] for r in cas])
  # read_excel('SURF_CHN_MUL_HOR_STATION.xlsx')
  # gdp()
  run_excel()
  run_shp()

Python关于excel和shp的使用在matplotlib

Python关于excel和shp的使用在matplotlib

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对三水点靠木的支持。如果你想了解更多相关内容请查看下面相关链接

Python 相关文章推荐
python中Flask框架简单入门实例
Mar 21 Python
在Python的Django框架中实现Hacker News的一些功能
Apr 17 Python
Python初学时购物车程序练习实例(推荐)
Aug 08 Python
解决python爬虫中有中文的url问题
May 11 Python
python使用wxpy实现微信消息防撤回脚本
Apr 29 Python
python和mysql交互操作实例详解【基于pymysql库】
Jun 04 Python
如何在Django项目中引入静态文件
Jul 26 Python
Python3 无重复字符的最长子串的实现
Oct 08 Python
Python aiohttp百万并发极限测试实例分析
Oct 26 Python
Python实现中英文全文搜索的示例
Dec 04 Python
解决python 执行shell命令无法获取返回值的问题
Dec 05 Python
从np.random.normal()到正态分布的拟合操作
Jun 02 Python
Python使用folium excel绘制point
Jan 03 #Python
Python获取航线信息并且制作成图的讲解
Jan 03 #Python
Python中GeoJson和bokeh-1的使用讲解
Jan 03 #Python
Python图像滤波处理操作示例【基于ImageFilter类】
Jan 03 #Python
python 调用有道api接口的方法
Jan 03 #Python
对python调用RPC接口的实例详解
Jan 03 #Python
Python图像的增强处理操作示例【基于ImageEnhance类】
Jan 03 #Python
You might like
PHP的FTP学习(一)
2006/10/09 PHP
Smarty模板快速入门
2007/01/04 PHP
php数组合并array_merge()函数使用注意事项
2014/06/19 PHP
PHP之uniqid()函数用法
2014/11/03 PHP
CodeIgniter分页类pagination使用方法示例
2016/03/28 PHP
ThinkPHP简单使用memcache缓存的方法
2016/11/15 PHP
PHP实现断点续传乱序合并文件的方法
2018/09/06 PHP
初学Javascript的一些总结
2008/11/03 Javascript
XHTML下,JS浮动代码失效的问题
2009/11/12 Javascript
Js与下拉列表处理问题解决
2014/02/13 Javascript
jquery中attr和prop的区别分析
2015/03/16 Javascript
js 判断所选时间(或者当前时间)是否在某一时间段的实现代码
2015/09/05 Javascript
原生JavaScript制作微博发布面板效果
2016/03/11 Javascript
浅析AngularJS中的指令
2016/03/20 Javascript
JS中的==运算: [''] == false —>true
2016/07/24 Javascript
使用JavaScript获取Request中参数的值方法
2016/09/27 Javascript
Jqprint实现页面打印
2017/01/06 Javascript
NodeJs使用Mysql模块实现事务处理实例
2017/05/31 NodeJs
jQuery EasyUI结合zTree树形结构制作web页面
2017/09/01 jQuery
微信小程序使用audio组件播放音乐功能示例【附源码下载】
2017/12/08 Javascript
swiper 解决动态加载数据滑动失效的问题
2018/02/26 Javascript
解决低版本的浏览器不支持es6的import问题
2018/03/09 Javascript
vue.js自定义组件directives的实例代码
2018/11/09 Javascript
微信小程序实现搜索历史功能
2020/03/26 Javascript
Nodejs libuv运行原理详解
2019/08/21 NodeJs
JS控制GIF图片的停止与显示
2019/10/24 Javascript
es6中class类静态方法,静态属性,实例属性,实例方法的理解与应用分析
2020/02/15 Javascript
vue打包npm run build时候界面报错的解决
2020/08/13 Javascript
python web框架学习笔记
2016/05/03 Python
详谈Python中列表list,元祖tuple和numpy中的array区别
2018/04/18 Python
django框架模板中定义变量(set variable in django template)的方法分析
2019/06/24 Python
Python Web程序搭建简单的Web服务器
2019/07/31 Python
对Django的restful用法详解(自带的增删改查)
2019/08/28 Python
20行Python代码实现视频字符化功能
2020/04/13 Python
利用pandas向一个csv文件追加写入数据的实现示例
2020/04/23 Python
即兴演讲稿
2014/01/04 职场文书