本文整理汇总了Python中mpl_toolkits.basemap.Basemap.hexbin方法的典型用法代码示例。如果您正苦于以下问题:Python Basemap.hexbin方法的具体用法?Python Basemap.hexbin怎么用?Python Basemap.hexbin使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mpl_toolkits.basemap.Basemap
的用法示例。
在下文中一共展示了Basemap.hexbin方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: draw_map
# 需要导入模块: from mpl_toolkits.basemap import Basemap [as 别名]
# 或者: from mpl_toolkits.basemap.Basemap import hexbin [as 别名]
def draw_map(lat, lng, sic):
# setup south polar stereographic basemap.
# The longitude lon_0 is at 6-o'clock, and the
# latitude circle boundinglat is tangent to the edge
# of the map at lon_0. Default value of lat_ts
# (latitude of true scale) is pole.
m = Basemap(projection='spstere',boundinglat=-50,lon_0=270,resolution='h', round=True)
# Basemap()
plt.figure()
for beam in range(8):
x1,y1 = m(lng[beam], lat[beam])
m.hexbin(x1,y1, C=sic[beam],gridsize=len(sic[beam]),cmap=plt.cm.jet)
m.drawcoastlines()
m.fillcontinents(color='coral',lake_color='aqua')
# draw parallels and meridians.
m.drawparallels(np.arange(-80.,81.,20.))
m.drawmeridians(np.arange(-180.,181.,20.))
m.drawmapboundary(fill_color='aqua')
m.colorbar(location="bottom",label="SIC") # draw colorbar
plt.title("North Polar Stereographic Projection")
plt.gcf().set_size_inches(18,10)
plt.show()
示例2: drawHk
# 需要导入模块: from mpl_toolkits.basemap import Basemap [as 别名]
# 或者: from mpl_toolkits.basemap.Basemap import hexbin [as 别名]
def drawHk(self, filename="nodet"):
# print sic
# setup south polar stereographic basemap.
if (len(self)!=0):
m = Basemap(projection='spstere',boundinglat=-50,lon_0=180,resolution='h', round=True)
lat = []
lng = []
sic = []
for s in self:
lng.append(s.getLon())
lat.append(s.getLat())
sic.append(s.getSic())
lng = np.array(lng)
lat = np.array(lat)
sic = np.array(sic)
plt.figure()
x1,y1= m(lng, lat)
print "x, y, sic", x1, y1, sic
m.hexbin(x1,y1, C=sic, gridsize=len(sic), cmap=plt.cm.jet)
m.drawcoastlines()
m.fillcontinents(lake_color='white')
# draw parallels and meridians.
m.drawparallels(np.arange(-80.,81.,20.))
m.drawmeridians(np.arange(-180.,181.,20.))
m.drawmapboundary(fill_color='green')
m.colorbar(location="right",label="SIC") # draw colorbar
plt.title("Sea Ice Concentration - South Pole")
fig = plt.gcf()
plt.show()
f_name = "./img/"+filename + "_.png"
fig.savefig(f_name)
plt.close()
# Delete auxiliar variables.
del m
del lng
del lat
del sic
del x1
del y1
return f_name
示例3: hexagon_map
# 需要导入模块: from mpl_toolkits.basemap import Basemap [as 别名]
# 或者: from mpl_toolkits.basemap.Basemap import hexbin [as 别名]
def hexagon_map(coordinates, temperature, hex_grid_size=(50,50)):
m = Basemap(projection='tmerc', lat_0=51, lon_0=10, llcrnrlat=47, llcrnrlon=5, urcrnrlat=55, urcrnrlon=16, resolution='i')
m.drawcoastlines()
m.drawcountries()
m.drawmapboundary()
lats = coordinates[:,0]
lons = coordinates[:,1]
x, y = m(lons, lats)
m.hexbin(x, y, C = temperature, gridsize=hex_grid_size, linewidth=0.5, edgecolor='k')
m.colorbar(location='bottom')
plt.show()
示例4: station_map
# 需要导入模块: from mpl_toolkits.basemap import Basemap [as 别名]
# 或者: from mpl_toolkits.basemap.Basemap import hexbin [as 别名]
def station_map(coordinates, temperature):
# map = Basemap(projection='lcc', lat_0 = 51, lon_0 = 10, resolution = 'i', width = 850000, height = 1000000)
map = Basemap(projection='tmerc', lat_0=51, lon_0=10, llcrnrlat=47, llcrnrlon=5, urcrnrlat=55, urcrnrlon=16, resolution='i')
map.drawcoastlines()
map.drawcountries()
map.drawmapboundary()
lats = coordinates[:,0]
lons = coordinates[:,1]
x, y = map(lons, lats)
# map.hexbin(x,y)
map.hexbin(x, y, C = temperature, gridsize=(9,9), linewidth=0.5, edgecolor='k')
map.colorbar(location='bottom')
plt.show()
示例5: hexagon_map
# 需要导入模块: from mpl_toolkits.basemap import Basemap [as 别名]
# 或者: from mpl_toolkits.basemap.Basemap import hexbin [as 别名]
def hexagon_map(coordinates, temperature, hex_grid_size=(50,50)):
m = Basemap(projection='tmerc', lat_0=51, lon_0=10, llcrnrlat=47, llcrnrlon=5, urcrnrlat=55, urcrnrlon=16, resolution='i')
lats = coordinates[:,0]
lons = coordinates[:,1]
x, y = m(lons, lats)
plt.ion()
for i in range(len(temperature)):
plt.clf()
m.drawcoastlines()
m.drawcountries()
m.drawmapboundary()
m.hexbin(x, y, C = temperature[:,i], gridsize=hex_grid_size, linewidth=0.5, edgecolor='k', vmin=np.amin(temperature), vmax=np.amax(temperature))
cb = m.colorbar(location='bottom', label='Random data')
plt.show()
plt.pause(0.005)
示例6: drawHkNPole
# 需要导入模块: from mpl_toolkits.basemap import Basemap [as 别名]
# 或者: from mpl_toolkits.basemap.Basemap import hexbin [as 别名]
def drawHkNPole(self, filename="nodet"):
if (len(self)!=0):
ms = Basemap(projection='npstere',boundinglat=50,lon_0=180,resolution='h', round=True)
lat = []
lng = []
sic = []
for s in self:
lng.append(s.getLon())
lat.append(s.getLat())
sic.append(s.getSic())
#print s.getLat(), s.getLon(), s.getSic()
lng = np.array(lng)
lat = np.array(lat)
sic = np.array(sic)
plt.figure()
x1,y1= ms(lng, lat)
ms.hexbin(x1,y1, C=sic, gridsize=len(sic), cmap=plt.cm.jet)
ms.drawcoastlines()
ms.fillcontinents(lake_color='green')
ms.drawparallels(np.arange(-80.,81.,20.))
ms.drawmeridians(np.arange(-180.,181.,20.))
ms.drawmapboundary(fill_color='white')
ms.colorbar(location="right",label="SIC") # draw colorbar
plt.title("Sea Ice south Concentration")
fig = plt.gcf()
plt.show()
f_name = "./img/"+filename + "S.png"
fig.savefig(f_name)
plt.close()
del ms
del lng
del lat
del sic
del x1
del y1
return f_name
示例7: hexagon_map
# 需要导入模块: from mpl_toolkits.basemap import Basemap [as 别名]
# 或者: from mpl_toolkits.basemap.Basemap import hexbin [as 别名]
def hexagon_map(station_lon, station_lat, station_val, hex_grid_size=(50,50)):
"""
Creates a map of values for different stations, using hexagons per station location.
Params:
station_lon (1D arrya): longitutes of station locations
station_lat (1D arrya): latitudes of station locations
station_val (1D arrya): values to plot per stations
hex_grid_size (tuple, optional): number of hexagons in x and y dimension
"""
m = Basemap(projection='tmerc', lat_0=51, lon_0=10, llcrnrlat=47, llcrnrlon=5, urcrnrlat=55, urcrnrlon=16, resolution='i')
#with open('germany_map.pkl', 'rb') as input:
#m = pickle.load(input) # open map from disk
m.drawcoastlines()
m.drawcountries()
m.drawmapboundary()
x, y = m(station_lon, station_lat)
m.hexbin(x, y, C = station_val, gridsize=hex_grid_size, linewidth=0.5, edgecolor='k', vmin=np.nanmin(station_val), vmax=np.nanmax(station_val))
#m.colorbar(location='bottom')
cb = m.colorbar(location='bottom', label='Random Data', ticks=[np.nanmin(station_val), 0, np.nanmax(station_val)])
plt.show()
示例8: drawNPole
# 需要导入模块: from mpl_toolkits.basemap import Basemap [as 别名]
# 或者: from mpl_toolkits.basemap.Basemap import hexbin [as 别名]
def drawNPole(self):
m = Basemap(projection='npstere',boundinglat=50,lon_0=270,resolution='h', round=True)
if (len(self._lats)==0):
self._fillvalues()
lng = self.getLonAsNp()
lat = self.getLatAsNp()
sic = self.getSicAsNp()
plt.figure()
x1,y1= m(lng, lat)
m.hexbin(x1,y1, C=sic, gridsize=len(sic), cmap=plt.cm.jet)
m.drawcoastlines()
m.drawcountries()
m.fillcontinents(color='coral')
m.drawmapboundary()
# draw parallels and meridians.
#m.drawparallels(np.arange(-80.,81.,20.))
#m.drawmeridians(np.arange(-180.,181.,20.))
#m.drawmapboundary(fill_color='white')
#m.colorbar(location="right",label="SIC") # draw colorbar
plt.title("Final")
#fig = plt.gcf()
plt.show()
plt.close()
# Delete auxiliar variables.
del m
del lng
del lat
del sic
del x1
del y1
示例9: zip
# 需要导入模块: from mpl_toolkits.basemap import Basemap [as 别名]
# 或者: from mpl_toolkits.basemap.Basemap import hexbin [as 别名]
for info, lightning in zip(map.lightnings_info, map.lightnings):
x.append(lightning[0])
y.append(lightning[1])
if float(info['amplitude']) < 0:
c.append(-1 * float(info['amplitude']))
else:
c.append(float(info['amplitude']))
plt.figure(0)
map.drawcoastlines()
map.readshapefile('../sample_files/comarques', 'comarques')
map.hexbin(array(x), array(y))
map.colorbar(location='bottom')
plt.figure(1)
map.drawcoastlines()
map.readshapefile('../sample_files/comarques', 'comarques')
map.hexbin(array(x), array(y), gridsize=20, mincnt=1, cmap='summer', bins='log')
map.colorbar(location='bottom', format='%.1f', label='log(# lightnings)')
示例10: m
# 需要导入模块: from mpl_toolkits.basemap import Basemap [as 别名]
# 或者: from mpl_toolkits.basemap.Basemap import hexbin [as 别名]
lats = np.compress(lats > 20, lats)
lons = np.compress(lats > 20, lons)
# convert to map projection coordinates.
x1, y1 = m(lons, lats)
# remove points outside projection limb.
x = np.compress(np.logical_or(x1 < 1.e20,y1 < 1.e20), x1)
y = np.compress(np.logical_or(x1 < 1.e20,y1 < 1.e20), y1)
# function to plot at those points.
xscaled = 4.*(x-0.5*(m.xmax-m.xmin))/m.xmax
yscaled = 4.*(y-0.5*(m.ymax-m.ymin))/m.ymax
z = xscaled*np.exp(-xscaled**2-yscaled**2)
# make plot using hexbin
fig = plt.figure(figsize=(12,5))
ax = fig.add_subplot(121)
CS = m.hexbin(x,y,C=z,gridsize=bins,cmap=plt.cm.jet)
# draw coastlines, lat/lon lines.
m.drawcoastlines()
m.drawparallels(np.arange(0,81,20))
m.drawmeridians(np.arange(-180,181,60))
m.colorbar() # draw colorbar
plt.title('hexbin demo')
# use histogram2d instead of hexbin.
ax = fig.add_subplot(122)
# remove points outside projection limb.
bincount, xedges, yedges = np.histogram2d(x, y, bins=bins)
mask = bincount == 0
# reset zero values to one to avoid divide-by-zero
bincount = np.where(bincount == 0, 1, bincount)
H, xedges, yedges = np.histogram2d(x, y, bins=bins, weights=z)
示例11: PolygonPatch
# 需要导入模块: from mpl_toolkits.basemap import Basemap [as 别名]
# 或者: from mpl_toolkits.basemap.Basemap import hexbin [as 别名]
figwidth = 14
fig = plt.figure(figsize=(figwidth, figwidth*h/w))
ax = fig.add_subplot(111, axisbg='w', frame_on=False)
# draw neighborhood patches from polygons
df_map['patches'] = df_map['poly'].map(lambda x: PolygonPatch(
x, fc='#555555', ec='#555555', lw=1, alpha=1, zorder=0))
# plot neighborhoods by adding the PatchCollection to the axes instance
ax.add_collection(PatchCollection(df_map['patches'].values, match_original=True))
# the mincnt argument only shows cells with a value >= 1
# The number of hexbins you want in the x-direction
numhexbins = 50
hx = m.hexbin(
np.array([geom.x for geom in city_points]),
np.array([geom.y for geom in city_points]),
gridsize=(numhexbins, int(numhexbins*h/w)), #critical to get regular hexagon, must stretch to map dimensions
bins='log', mincnt=1, edgecolor='none', alpha=1.,
cmap=plt.get_cmap('Blues'))
# Draw the patches again, but this time just their borders (to achieve borders over the hexbins)
df_map['patches'] = df_map['poly'].map(lambda x: PolygonPatch(
x, fc='none', ec='#FFFF99', lw=1, alpha=1, zorder=1))
ax.add_collection(PatchCollection(df_map['patches'].values, match_original=True))
# Draw a map scale
m.drawmapscale(coords[0] + 0.05, coords[1] - 0.01,
coords[0], coords[1], 4.,
units='mi', barstyle='fancy', labelstyle='simple',
fillcolor1='w', fillcolor2='#555555', fontcolor='#555555',
zorder=5)
示例12: plot
# 需要导入模块: from mpl_toolkits.basemap import Basemap [as 别名]
# 或者: from mpl_toolkits.basemap.Basemap import hexbin [as 别名]
def plot(
self, data, bbox=None, plot_type='scatter',
fig_kwargs=None, bmap_kwargs=None, plot_kwargs=None,
cbar_kwargs=None):
"""
Plot an array of data on a map using matplotlib and Basemap,
automatically matching the data to node positions.
Keyword arguments are passed to the plotting routine.
Parameters
----------
data : pandas.Series
Numeric data with the same length and index as the nodes
in the network.
bbox : tuple, optional
(lat_min, lng_min, lat_max, lng_max)
plot_type : {'hexbin', 'scatter'}, optional
fig_kwargs : dict, optional
Keyword arguments that will be passed to
matplotlib.pyplot.subplots. Use this to specify things like
figure size or background color.
bmap_kwargs : dict, optional
Keyword arguments that will be passed to the Basemap constructor.
This can be used to specify a projection or coastline resolution.
plot_kwargs : dict, optional
Keyword arguments that will be passed to the matplotlib plotting
command used. Use this to control plot styles and color maps used.
cbar_kwargs : dict, optional
Keyword arguments passed to the Basemap.colorbar method.
Use this to control color bar location and label.
Returns
-------
bmap : Basemap
fig : matplotlib.Figure
ax : matplotlib.Axes
"""
from mpl_toolkits.basemap import Basemap
fig_kwargs = fig_kwargs or {}
bmap_kwargs = bmap_kwargs or {}
plot_kwargs = plot_kwargs or {}
cbar_kwargs = cbar_kwargs or {}
if not bbox:
bbox = (
self.nodes_df.y.min(),
self.nodes_df.x.min(),
self.nodes_df.y.max(),
self.nodes_df.x.max())
fig, ax = plt.subplots(**fig_kwargs)
bmap = Basemap(
bbox[1], bbox[0], bbox[3], bbox[2], ax=ax, **bmap_kwargs)
bmap.drawcoastlines()
bmap.drawmapboundary()
x, y = bmap(self.nodes_df.x.values, self.nodes_df.y.values)
if plot_type == 'scatter':
plot = bmap.scatter(
x, y, c=data.values, **plot_kwargs)
elif plot_type == 'hexbin':
plot = bmap.hexbin(
x, y, C=data.values, **plot_kwargs)
bmap.colorbar(plot, **cbar_kwargs)
return bmap, fig, ax
示例13: open
# 需要导入模块: from mpl_toolkits.basemap import Basemap [as 别名]
# 或者: from mpl_toolkits.basemap.Basemap import hexbin [as 别名]
flash_lat = np.concatenate([flash_lat,datafile.variables['lightning_flash_lat'][:]]) #add to array
flash_lon = np.concatenate([flash_lon,datafile.variables['lightning_flash_lon'][:]]) #add to array
#Create CSV files of values from the populated flash_lat/lon arrays
with open(csvfile, 'wb') as myfile:
writer = csv.writer(myfile)
writer.writerows(izip(["flash_lat"], ["flash_lon"])) #Define headers in row (izip creates columns)
writer.writerows(izip(flash_lat,flash_lon)) #Define data rows (izip creates columns)
#Create plot of lightning flash location heat map
plt.figure(figsize=((20,20))) #Set plot dimensions
map = Basemap(projection='cyl', lon_0 = 0, resolution='c')
lightning = map.hexbin(flash_lon, flash_lat, gridsize=300,bins='log',cmap='jet',mincnt=1,zorder=10) #Bin flash counts into hexbins using a gridsize of your choice
#Draw geographic boundaries and meridians/parallels
map.drawmapboundary(fill_color='k')
map.fillcontinents(color='grey',lake_color='grey')
map.drawcoastlines(color='white')
map.drawcountries(color='white')
map.drawmeridians(np.arange(0,390,30), labels=[0,0,0,1],fontsize=10, color="lightgray")
map.drawparallels(np.arange(-90,120,30), labels=[1,0,0,0],fontsize=10, color="lightgray")
cbar = map.colorbar(lightning,location='bottom',pad="5%")
cbar.set_label('Flash Count') #Remember to change label
plt.title('ISS LIS Detected Lightning Flash Locations January 4, 2018', fontsize = 18) #Rember to change title
示例14: Basemap
# 需要导入模块: from mpl_toolkits.basemap import Basemap [as 别名]
# 或者: from mpl_toolkits.basemap.Basemap import hexbin [as 别名]
points_x = np.array([x['X'] for i,x in merge.iterrows()])
points_y = np.array([x['Y'] for i,x in merge.iterrows()])
c = np.array([x['internet'] for i,x in merge.iterrows()])
# Trentino's boundingbox
a = (45.6730682227551, 10.4521594968354)
b = (46.5327699992773, 11.9627133503828)
# Trentino shapefile
# http://dati.trentino.it/dataset/limite-comprensoriale-027140/resource/ff1f1687-3f8f-427e-84d9-cf40c8b9b98a
m = Basemap(lat_0 = (a[0]+b[0])/2, lon_0 = (a[1]+b[1])/2, epsg=4326, llcrnrlon=a[1],llcrnrlat=a[0],urcrnrlon=b[1],urcrnrlat=b[0],)
m.readshapefile('nature/amm','Trentino_shapefile', color='0.35')
cmap = LinearSegmentedColormap.from_list("skil", sns.color_palette("RdBu_r", 7)[1:])
plt.register_cmap(cmap=cmap)
m.hexbin(points_x, points_y, cmap="skil", gridsize=50, C=c, bins='log', mincnt=1)
sns.despine(left=True, bottom=True)
plt.savefig('map.pdf', format='pdf', dpi=330, bbox_inches='tight')
# Import the dataset - social pulse, obtained from the geojson
social_df = pd.read_csv('nature/result2.csv', sep=',', encoding="utf-8-sig", parse_dates=['created'])
points_x = np.array([x['geomPoint.geom/coordinates/0'] for i,x in social_df.iterrows()])
points_y = np.array([x['geomPoint.geom/coordinates/1'] for i,x in social_df.iterrows()])
m = Basemap(lat_0 = (a[0]+b[0])/2, lon_0 = (a[1]+b[1])/2, epsg=4326, llcrnrlon=a[1], llcrnrlat=a[0], urcrnrlon=b[1], urcrnrlat=b[0],)
m.readshapefile('nature/amm', 'Trentino_shapefile', color='0.35')
m.hexbin(points_x, points_y, cmap="skil", gridsize=50, bins='log', mincnt=1)
sns.despine(left=True, bottom=True)
plt.savefig('map_social.pdf', format='pdf', dpi=330,bbox_inches='tight')
示例15: Basemap
# 需要导入模块: from mpl_toolkits.basemap import Basemap [as 别名]
# 或者: from mpl_toolkits.basemap.Basemap import hexbin [as 别名]
Data file tweets.dat contains binary lon/lat data only
Author: Kelsey Jordahl, Enthought
Scipy 2013 geospatial tutorial
"""
import os
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib import cm
N = 405146
west, south, east, north = -74.26, 40.50, -73.70, 40.92
#west, south, east, north = -74.03, 40.69, -73.93, 40.82
cwd = os.path.dirname(os.path.abspath(__file__))
datadir = os.path.join(os.path.split(cwd)[0], 'data')
tweetfile = os.path.join(datadir, 'tweets.dat')
ll = np.dtype([('lon', np.float32), ('lat', np.float32)])
tweets = np.memmap(tweetfile, dtype=ll, mode='r', shape=(N,))
fig = plt.figure()
ax = fig.add_subplot(111)
m = Basemap(projection='merc', llcrnrlat=south, urcrnrlat=north,
llcrnrlon=west, urcrnrlon=east, lat_ts=south, resolution='i')
x, y = m(tweets['lon'], tweets['lat'])
m.hexbin(x, y, gridsize=400,
bins='log', cmap=cm.YlOrRd_r)
plt.title("Twitter Heatmap")
plt.savefig('tweets.png', dpi=300, bbox_inches='tight')
plt.show()