# -*- coding: utf-8 -*-
'''
Created on Sat Sep 19 16:22:59 2015
@author: liangxw
'''
from __future__ import division
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
from mpl_toolkits.basemap import Basemap
from matplotlib.font_manager import FontProperties #使能够显示中文
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14) #设置中文字体的路径和大小
fig = plt.figure()
ax1 = fig.add_axes([0.10, 0.10, 0.80, 0.8]) #用于绘制地图
ax2 = fig.add_axes([0.85, 0.10, 0.04, 0.8]) #用于绘制colorbar
#首先绘制地图
map = Basemap(projection = 'cyl', #投影方式
resolution = 'l', #分辨率
llcrnrlon = 115.0, llcrnrlat = 29.7, urcrnrlon = 119.6, urcrnrlat = 34.3, #经纬度范围,460*460的网格
ax=ax1) #绘制区域
shapeinfo = map.readshapefile('bou2_4p', 'bou2_4p') #叠加行政区划
#添加横纵经纬网格线条
map.drawparallels(np.arange(30,34+1), labels=[1,0,0,0]) #四个labels分别表示左右上下
map.drawmeridians(np.arange(115,119+1), labels=[0,0,0,1])
#之后在地图上绘制数据
#首先生成460*460的经纬度网格
lons = np.arange(115.0, 119.6, 0.01)
lats = np.arange( 34.3, 29.7, -0.01)
X, Y = np.meshgrid(lons, lats)
levels=[0,3,6,10,20,30,40,50,60,80,100,200] #色标范围
#自定义色标值
colors=(np.array([255,255,255])/255, np.array([102,153,255])/255, np.array([ 0, 0,255])/255, np.array([ 51,204,102])/255,
np.array([ 0,102, 51])/255, np.array([204,255,102])/255, np.array([255,255, 0])/255, np.array([153,102, 51])/255,
np.array([255,153,102])/255, np.array([255,102,153])/255, np.array([250, 0, 0])/255)
#绘制数据
cf = map.contourf( X, Y, Data/5,levels,colors=colors)
#最后绘制colorbar
#方法1
cb = map.colorbar(cf,"right", size="5%", pad='2%',ticks=levels)
plt.title(u'方式1',fontproperties=font)
#ax1.set_title(u'方式1',fontproperties=font)
#方法2
cmap = mpl.colors.ListedColormap(colors[:-1])cmap.set_over((250/255, 0, 0))cb = mpl.colorbar.ColorbarBase(ax2, cmap=cmap,orientation='vertical',extend='max')cb.set_ticks((0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1))cb.set_ticklabels( ('0','3','6','10','20','30','40','50','60','80','100mm/h'))ax1.set_title(u'方式2',fontproperties=font)