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基础教程之缩进介绍
Aug 29 Python
分析Python编程时利用wxPython来支持多线程的方法
Apr 07 Python
Python  pip安装lxml出错的问题解决办法
Feb 10 Python
浅谈使用Python变量时要避免的3个错误
Oct 30 Python
Django中使用celery完成异步任务的示例代码
Jan 23 Python
利用Python+Java调用Shell脚本时的死锁陷阱详解
Jan 24 Python
学习python分支结构
May 17 Python
python面试题Python2.x和Python3.x的区别
May 28 Python
Python使用字典实现的简单记事本功能示例
Aug 15 Python
将keras的h5模型转换为tensorflow的pb模型操作
May 25 Python
Python数据分析之pandas函数详解
Apr 21 Python
Python多个MP4合成视频的实现方法
Jul 16 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实现插入排序?
2013/04/10 PHP
php不写闭合标签的好处
2014/03/04 PHP
php返回json数据函数实例
2014/10/09 PHP
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 2611816 bytes)
2014/11/08 PHP
php 5.6版本中编写一个PHP扩展的简单示例
2015/01/20 PHP
php实现的证件照换底色功能示例【人像抠图/换背景图】
2020/05/29 PHP
js 限制数字 js限制输入实现代码
2012/12/04 Javascript
Json和Jsonp理论实例代码详解
2013/11/15 Javascript
利用jquery写的左右轮播图特效
2014/02/12 Javascript
动态读取JSON解析键值对的方法
2014/06/03 Javascript
AngularJS辅助库browserTrigger用法示例
2016/11/03 Javascript
纯js三维数组实现三级联动效果
2017/02/07 Javascript
JavaScript引用类型Array实例分析
2018/07/24 Javascript
Bootstrap Table列宽拖动的方法
2018/08/15 Javascript
JavaScript定时器常见用法实例分析
2019/11/15 Javascript
antd-mobile ListView长列表的数据更新遇到的坑
2020/04/08 Javascript
win与linux系统中python requests 安装
2016/12/04 Python
详解python eval函数的妙用
2017/11/16 Python
python取数作为临时极大值(极小值)的方法
2018/10/15 Python
python3+pyqt5+itchat微信定时发送消息的方法
2019/02/20 Python
Python3实现的反转单链表算法示例
2019/03/08 Python
Python入门Anaconda和Pycharm的安装和配置详解
2019/07/16 Python
如何在django中运行scrapy框架
2020/04/22 Python
python如何使用腾讯云发送短信
2020/09/17 Python
H5 video poster属性设置视频封面的方法
2020/05/25 HTML / CSS
马来西亚演唱会订票网站:StubHub马来西亚
2018/10/18 全球购物
android面试问题与答案
2016/12/27 面试题
什么是TCP/IP
2014/07/27 面试题
小组合作学习反思
2014/02/18 职场文书
会计岗位职责范本
2014/03/07 职场文书
预备党员公开承诺书
2014/05/28 职场文书
2014年办公室主任工作总结
2014/11/12 职场文书
辣妈辣妹观后感
2015/06/10 职场文书
祝寿主持词
2015/07/02 职场文书
导游词之介休绵山
2019/12/31 职场文书
《杜鹃的婚约》OP主题曲「凸凹」无字幕影像公开
2022/04/08 日漫