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 的描述符 descriptor详解
Feb 27 Python
Python内置函数 next的具体使用方法
Nov 24 Python
Python+Turtle动态绘制一棵树实例分享
Jan 16 Python
详解Python3.6安装psutil模块和功能简介
May 30 Python
python将txt文档每行内容循环插入数据库的方法
Dec 28 Python
python+numpy按行求一个二维数组的最大值方法
Jul 09 Python
pandas的排序和排名的具体使用
Jul 31 Python
Python中BeautifuSoup库的用法使用详解
Nov 15 Python
浅谈python量化 双均线策略(金叉死叉)
Jun 03 Python
python怎么自定义捕获错误
Jun 29 Python
python两种获取剪贴板内容的方法
Nov 06 Python
详细总结Python常见的安全问题
May 21 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获取数组中重复最多的元素的实现方法
2014/11/11 PHP
PHP实现事件机制实例分析
2015/06/26 PHP
WordPress开发中的get_post_custom()函数使用解析
2016/01/04 PHP
Laravel框架实现利用中间件进行操作日志记录功能
2018/06/06 PHP
Javascript学习笔记一 之 数据类型
2010/12/15 Javascript
JavaScript日期时间与时间戳的转换函数分享
2015/01/31 Javascript
jQuery统计指定子元素数量的方法
2015/03/17 Javascript
Highcharts学习之坐标轴
2016/08/02 Javascript
前端面试知识点锦集(JavaScript篇)
2016/12/28 Javascript
javaScript生成支持中文带logo的二维码(jquery.qrcode.js)
2017/01/03 Javascript
Vue学习笔记进阶篇之单元素过度
2017/07/19 Javascript
浅谈JS获取元素的N种方法及其动静态讨论
2017/08/25 Javascript
angular4 JavaScript内存溢出问题
2018/03/06 Javascript
jquery实现的放大镜效果示例
2020/02/24 jQuery
JavaScript的一些小技巧分享
2021/01/06 Javascript
[03:49]DOTA2英雄基础教程 光之守卫
2014/01/14 DOTA
python操作xml文件示例
2014/04/07 Python
python类和函数中使用静态变量的方法
2015/05/09 Python
使用Python的Twisted框架编写非阻塞程序的代码示例
2016/05/25 Python
Python使用googletrans报错的解决方法
2018/09/25 Python
python print输出延时,让其立刻输出的方法
2019/01/07 Python
Pycharm之快速定位到某行快捷键的方法
2019/01/20 Python
对python函数签名的方法详解
2019/01/22 Python
Python 写入训练日志文件并控制台输出解析
2019/08/13 Python
Python写捕鱼达人的游戏实现
2020/03/31 Python
Python3爬虫mitmproxy的安装步骤
2020/07/29 Python
Mio Skincare英国官网:身体紧致及孕期身体护理
2018/08/19 全球购物
学前教育毕业生自荐信
2013/10/29 职场文书
财务部岗位职责
2013/11/19 职场文书
食品安全标语
2014/06/07 职场文书
我爱家乡演讲稿
2014/09/12 职场文书
2014年优秀党员材料
2014/12/18 职场文书
2016年暑假家长对孩子评语
2015/12/01 职场文书
浅谈golang package中init方法的多处定义及运行顺序问题
2021/05/06 Golang
微信小程序实现聊天室功能
2021/06/14 Javascript
Python编程源码报错解决方法总结经验分享
2021/10/05 Python