本文整理汇总了Python中matplotlib.pyplot.normalize函数的典型用法代码示例。如果您正苦于以下问题:Python normalize函数的具体用法?Python normalize怎么用?Python normalize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了normalize函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: normalize_colors
def normalize_colors(vmin, vmax, clip=False):
"""Helper to handle matplotlib API"""
import matplotlib.pyplot as plt
try:
return plt.Normalize(vmin, vmax, clip=clip)
except AttributeError:
return plt.normalize(vmin, vmax, clip=clip)
示例2: normalize_colors
def normalize_colors(vmin, vmax, clip=False):
"""Helper to handle matplotlib API"""
import matplotlib.pyplot as plt
if 'Normalize' in vars(plt):
return plt.Normalize(vmin, vmax, clip=clip)
else:
return plt.normalize(vmin, vmax, clip=clip)
示例3: plot_veg_types
def plot_veg_types(yc, xc, Cv, baresoil):
Projection_Parameters = projection
labels = ['Evergreen Needleleaf', 'Evergreen Broadleaf',
'Deciduous Needleleaf', 'Deciduous Broadleaf', 'Mixed Cover',
'Woodland', 'Wooded Grasslands', 'Closed Shrublands',
'Open Shrublands', 'Grasslands', 'Crop land', 'Bare Soil/Ice']
fig = plt.figure(figsize=(10, 12))
gs1 = gridspec.GridSpec(4, 3)
for loc in xrange(11):
ax = fig.add_subplot(gs1[loc])
c = plot_map(ax, yc, xc, Cv[loc], Projection_Parameters, vmin=0,
cmap='Jet')
ax.set_title(labels[loc])
ax = fig.add_subplot(gs1[11])
c = plot_map(ax, yc, xc, baresoil, Projection_Parameters, vmin=0,
cmap='Jet')
ax.set_title(labels[11])
sm = plt.cm.ScalarMappable(cmap='Jet', norm=plt.normalize(vmin=0, vmax=1))
colorbar_ax = fig.add_axes([0.92, 0.1, 0.03, 0.8])
sm._A = []
plt.colorbar(sm, cax=colorbar_ax)
fig.suptitle('Fraction of Vegetation Type', fontsize=20, fontweight='bold')
fig.text(0.5, 0.93, 'Regional Arctic Climate Model',
ha='center', fontsize=18)
plt.show()
示例4: buildHeatmap
def buildHeatmap(dataDictionary,title,bartitle,barcolor,barmin,barmax):
# Lambert Conformal map of USA lower 48 states
geoMap = Basemap(llcrnrlon=-119, llcrnrlat=22, urcrnrlon=-64,
urcrnrlat=49, projection='lcc', lat_1=33, lat_2=45,
lon_0=-95, resolution='i', area_thresh=10000)
# Uses a Shape File from the US Census Bureau
# http://www2.census.gov/geo/tiger/GENZ2010/
shapeInfo = geoMap.readshapefile('data/shape_files/gz_2010_us_040_00_500k','states',drawbounds=False)
# Process based off an example from our professor's lecture slides,
# James Bagrow - UVM Spring 2014
# http://bagrow.com/dsv/
# I took the base idea and modified it heavily for the needs
# of this project.
# Color each state based on Population
colors={}
statenames=[]
# Use the Green color map.
# Others may be found here : http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
colorMap = barcolor
heatmapMinAmt = barmin; heatmapMaxAmt = barmax # Range for Heatmap (Valuewise)
scalarMapping = plt.cm.ScalarMappable(cmap=colorMap,norm=plt.normalize(vmin=heatmapMinAmt, vmax=heatmapMaxAmt))
for shapedict in geoMap.states_info:
statename = shapedict['NAME']
# Grab population info for each state
try:
population = float(dataDictionary[statename])
except KeyError:
population = 0.0
# Define the color for this state.
# Population / Max Color Amt.
colors[statename] = colorMap((population-heatmapMinAmt)/(heatmapMaxAmt-heatmapMinAmt))
statenames.append(statename)
# Actually color each state in this structure.
for nshape, seg in enumerate(geoMap.states):
xx, yy = zip(*seg)
color = rgb2hex(colors[statenames[nshape]])
plt.fill(xx,yy,color,edgecolor=color)
# Bound our map to the continental US.
# otherwise, we'll have some weird display issues
# with Alaska and Hawaii.
geoMap.drawparallels(np.arange(25,65,20),labels=[0,0,0,0],zorder=-1,color="w")
geoMap.drawmeridians(np.arange(-120,-40,20),labels=[0,0,0,0],zorder=-1,color="w")
# Build the Color Bar at the bottom of the graph
mm = plt.cm.ScalarMappable(cmap=colorMap)
mm.set_array([heatmapMinAmt,heatmapMaxAmt])
plt.colorbar(mm, label=bartitle,ticks=[0,5000,10000,15000,20000,25000],
orientation="horizontal",fraction=0.05)
# Adjust size of image
plt.gcf().set_size_inches(12.0,8.0)
plt.gca().axis("off")
# Add Title and show.
plt.title(title)
plt.show()
示例5: showOverlapTable
def showOverlapTable(modes_x, modes_y, **kwargs):
"""Show overlap table using :func:`~matplotlib.pyplot.pcolor`. *modes_x*
and *modes_y* are sets of normal modes, and correspond to x and y axes of
the plot. Note that mode indices are incremented by 1. List of modes
is assumed to contain a set of contiguous modes from the same model.
Default arguments for :func:`~matplotlib.pyplot.pcolor`:
* ``cmap=plt.cm.jet``
* ``norm=plt.normalize(0, 1)``"""
import matplotlib.pyplot as plt
overlap = abs(calcOverlap(modes_y, modes_x))
if overlap.ndim == 0:
overlap = np.array([[overlap]])
elif overlap.ndim == 1:
overlap = overlap.reshape((modes_y.numModes(), modes_x.numModes()))
cmap = kwargs.pop('cmap', plt.cm.jet)
norm = kwargs.pop('norm', plt.normalize(0, 1))
show = (plt.pcolor(overlap, cmap=cmap, norm=norm, **kwargs),
plt.colorbar())
x_range = np.arange(1, modes_x.numModes() + 1)
plt.xticks(x_range-0.5, x_range)
plt.xlabel(str(modes_x))
y_range = np.arange(1, modes_y.numModes() + 1)
plt.yticks(y_range-0.5, y_range)
plt.ylabel(str(modes_y))
plt.axis([0, modes_x.numModes(), 0, modes_y.numModes()])
if SETTINGS['auto_show']:
showFigure()
return show
示例6: discrete_calldata_colormesh
def discrete_calldata_colormesh(X, labels=None, colors='wbgrcmyk', states=None, ax=None, **kwargs):
"""
Make a meshgrid from discrete calldata (e.g., genotypes).
Parameters
----------
X: array
2-dimensional array of integers of shape (#variants, #samples)
labels: sequence of strings
Axis labels (e.g., sample IDs)
colors: sequence
Colors to use for different values of the array
states: sequence
Manually specify discrete calldata states (if not given will be determined from the data)
ax: axes
Axes on which to draw
Remaining keyword arguments are passed to ax.pcolormesh.
"""
# set up axes
if ax is None:
fig = plt.figure(figsize=(7, 5))
ax = fig.add_subplot(111)
# determine discrete states
if states is None:
states = np.unique(X)
colors = colors[:max(states)-min(states)+1] # only need as many colors as states
# plotting defaults
pltargs = {
'cmap': ListedColormap(colors),
'norm': plt.normalize(min(states), max(states)+1),
}
pltargs.update(kwargs)
ax.pcolormesh(X.T, **pltargs)
ax.set_xlim(0, X.shape[0])
ax.set_ylim(0, X.shape[1])
ax.set_yticks(np.arange(X.shape[1]) + .5)
if labels is not None:
# labels = ['%s [%s] ' % (s, i) for (i, s) in enumerate(labels)]
ax.set_yticklabels(labels, rotation=0)
return ax
示例7: coRes
def coRes(self):
layers = self.iface.legendInterface().layers()
for ly in layers:
if ly.name() == 'r1d_in_data':
vl2 = ly
print vl2.name()
x=[]
y=[]
values =[]
ab = self.dockwidget.txtAB2CoRes.text()
print ab
for f in vl2.getFeatures():
#print f['ab2']
if f['ab2'] == float(ab):
geom = f.geometry()
x.append(geom.asPoint().x())
y.append(geom.asPoint().y())
values.append(f['ra'])
#Creating the output grid (100x100, in the example)
#x = [10,60,40,70,10,50,20,70,30,60]
#y = [10,20,30,30,40,50,60,70,80,90]
#values = [1,2,2,3,4,6,7,7,8,10]
print x
print y
#print xx
txi = np.linspace(min(x), max(x), 10000)
tyi = np.linspace(min(y), max(y), 10000)
XI, YI = np.meshgrid(ti, ti)
#Creating the interpolation function and populating the output matrix value
rbf = Rbf(x, y, values, function='inverse')
ZI = rbf(XI, YI)
# Plotting the result
n = plt.normalize(0.0, 1000.0)
plt.subplot(1, 1, 1)
plt.pcolor(XI, YI, ZI)
plt.scatter(x, y, 1000, values)
plt.title('RBF interpolation')
plt.xlim(min(x), max(x))
plt.ylim(min(y), max(y))
plt.colorbar()
plt.show()
示例8: showOverlapTable
def showOverlapTable(rows, cols, **kwargs):
"""Show overlap table using :func:`~matplotlib.pyplot.pcolor`. *rows* and
*cols* are sets of normal modes, and correspond to rows and columns of the
displayed overlap matrix. Note that mode indices are incremented by 1.
List of modes should contain a set of contiguous modes from the same model.
Default arguments for :func:`~matplotlib.pyplot.pcolor`:
* ``cmap=plt.cm.jet``
* ``norm=plt.normalize(0, 1)``
.. plot::
:context:
:include-source:
plt.figure(figsize=(5,4))
showOverlapTable( p38_pca[:6], p38_anm[:6] )
plt.title('p38 PCA vs ANM')
.. plot::
:context:
:nofigs:
plt.close('all')"""
import matplotlib.pyplot as plt
overlap = abs(calcOverlap(rows, cols))
if isinstance(rows, NMA):
rows = rows[:]
if isinstance(cols, NMA):
cols = cols[:]
cmap = kwargs.pop('cmap', plt.cm.jet)
norm = kwargs.pop('norm', plt.normalize(0, 1))
show = (plt.pcolor(overlap, cmap=cmap, norm=norm, **kwargs),
plt.colorbar())
x_range = np.arange(1, len(cols)+1)
plt.xticks(x_range-0.5, x_range)
plt.xlabel(str(cols))
y_range = np.arange(1, len(rows)+1)
plt.yticks(y_range-0.5, y_range)
plt.ylabel(str(rows))
plt.axis([0, len(cols), 0, len(rows)])
return show
示例9: quick_ortho_plot
def quick_ortho_plot(x,y,z, bbox=[], loc=None, title='', norm=None):
import matplotlib.pyplot as pp
import xipy.volume_utils as vu
from xipy.vis.single_slice_plot import SliceFigure
# find or make the x, y, z plane extents
if bbox:
extents = vu.limits_to_extents(bbox)
else:
extents = [ reduce(lambda x,y: x+y, zip([0,0],p.shape[:2][::-1]))
for p in (x, y, z) ]
if norm is None and len(x.shape) < 3:
mx = max([ x.max(), y.max(), z.max() ])
mn = min([ x.min(), y.min(), z.min() ])
norm = pp.normalize(mn, mx)
fig = pp.figure()
loc = list(loc)
zloc = loc[0],loc[1] if loc else None
ax_z = fig.add_subplot(131)
sf_z = SliceFigure(fig, extents[2])
img_z = sf_z.spawn_image(z, extent=extents[2], loc=zloc,
interpolation='nearest', norm=norm)
ax_z.set_title('plot z')
yloc = loc[0],loc[2] if loc else None
ax_y = fig.add_subplot(132)
sf_y = SliceFigure(fig, extents[1])
img_y = sf_y.spawn_image(y, extent=extents[1], loc=yloc,
interpolation='nearest', norm=norm)
ax_y.set_title('plot y')
xloc = loc[1],loc[2] if loc else None
ax_x = fig.add_subplot(133)
sf_x = SliceFigure(fig, extents[0])
img_x = sf_x.spawn_image(x, extent=extents[0], loc=xloc,
interpolation='nearest', norm=norm)
ax_x.set_title('plot x')
if title:
fig.text(.5, .05, title, ha='center')
pp.colorbar(img_x.img)
pp.show()
return fig
示例10: draw
def draw():
global m, learn, z
pyp.background(200,50)
learn.collect_data()
m = learn.get_mean()
pyp.loadPixels()
m = np.atleast_2d(m)
norm = normalize(vmin=min(min(m)), vmax=max(max(m)))
cmap = get_cmap('jet')
m_normed = norm(m)
rgba_data=cmap(m_normed)*255
r = rgba_data[0,:,0].astype('uint32')
g = rgba_data[0,:,1].astype('uint32')
b = rgba_data[0,:,2].astype('uint32')
a = rgba_data[0,:,3].astype('uint32')
pyp.screen.pixels = a << 24 | r << 16 | g << 8 | b
pyp.updatePixels()
示例11: find_image_threshold
def find_image_threshold(arr, percentile=90., debug=False):
nbins = 200
bsizes, bpts = np.histogram(arr.flatten(), bins=nbins)
# heuristically, this should show up near the middle of the
# second peak of the intensity histogram
start_pt = np.abs(bpts - arr.max()/2.).argmin()
db = np.diff(bsizes[:start_pt])
## zcross = np.argwhere((db[:-1] < 0) & (db[1:] >= 0)).flatten()[0]
bval = bsizes[1:start_pt-1][ (db[:-1] < 0) & (db[1:] >= 0) ].min()
zcross = np.argwhere(bval==bsizes).flatten()[0]
thresh = (bpts[zcross] + bpts[zcross+1])/2.
# interpolate the percentile value from the bin edges
bin_lo = int(percentile * nbins / 100.0)
bin_hi = int(round(percentile * nbins / 100.0 + 0.5))
p_hi = percentile - bin_lo # proportion of hi bin
p_lo = bin_hi - percentile # proportion of lo bin
## print bin_hi, bin_lo, p_hi, p_lo
pval = bpts[bin_lo] * p_lo + bpts[bin_hi] * p_hi
if debug:
import matplotlib as mpl
import matplotlib.pyplot as pp
f = pp.figure()
ax = f.add_subplot(111)
ax.hist(arr.flatten(), bins=nbins)
l = mpl.lines.Line2D([thresh, thresh], [0, .25*bsizes.max()],
linewidth=2, color='r')
ax.add_line(l)
ax.xaxis.get_major_formatter().set_scientific(True)
f = pp.figure()
norm = pp.normalize(0, pval)
ax = f.add_subplot(211)
plot_arr = arr
while len(plot_arr.shape) > 2:
plot_arr = plot_arr[plot_arr.shape[0]/2]
ax.imshow(plot_arr, norm=norm)
ax = f.add_subplot(212)
simple_mask = (plot_arr < thresh)
ax.imshow(np.ma.masked_array(plot_arr, mask=simple_mask), norm=norm)
pp.show()
return thresh, pval
示例12: range
leg = ax.legend([l1, l2, l3], labels, ncol=3, frameon=False, fontsize=16,
bbox_to_anchor=[1.1, 0.11], handlelength=2,
handletextpad=1, columnspacing=2, title='Average Page Size')
# Customize legend title
# Set position to increase space between legend and labels
plt.setp(leg.get_title(), fontsize=20, alpha=a)
leg.get_title().set_position((0, 10))
# Customize transparency for legend labels
[plt.setp(label, alpha=a) for label in leg.get_texts()]
# Create a fake colorbar
ctb = LinearSegmentedColormap.from_list('custombar', customcmap, N=2048)
# Trick from http://stackoverflow.com/questions/8342549/
# matplotlib-add-colorbar-to-a-sequence-of-line-plots
sm = plt.cm.ScalarMappable(cmap=ctb, norm=plt.normalize(vmin=1, vmax=3))
# Fake up the array of the scalar mappable
sm._A = []
# Set colorbar, aspect ratio
cbar = plt.colorbar(sm, alpha=0.05, aspect=16, shrink=0.4)
cbar.solids.set_edgecolor("face")
# Remove colorbar container frame
cbar.outline.set_visible(False)
# Fontsize for colorbar ticklabels
cbar.ax.tick_params(labelsize=16)
# Customize colorbar tick labels
mytks = range(1,4,1)
cbar.set_ticks(mytks)
cbar.ax.set_yticklabels([str(i) for i in mytks], alpha=a)
示例13: vectorize
def vectorize(hillshade_file, m_value_file):
import matplotlib.pyplot as pp
import numpy as np
import matplotlib.colors as colors
import matplotlib.cm as cmx
from matplotlib import rcParams
# get data
hillshade, hillshade_header = read_flt(hillshade_file)
m_values, m_values_header = read_flt(m_value_file)
# handle plotting hillshades which are larger than the m_value raster
# cannot cope with m_value raster larger than the hillshade
corrected_x = 0
corrected_y = 0
if (hillshade_header[0] != m_values_header[0]) or (hillshade_header[1] != m_values_header[1]):
corrected_x = (m_values_header[2] - hillshade_header[2]) / hillshade_header[4]
corrected_y = (
((m_values_header[3] / m_values_header[4]) + m_values_header[1])
- ((hillshade_header[3] / hillshade_header[4]) + hillshade_header[1])
) * -1
# ignore nodata values
hillshade = np.ma.masked_where(hillshade == -9999, hillshade)
m_values = np.ma.masked_where(m_values == -9999, m_values)
# fonts
rcParams["font.family"] = "sans-serif"
rcParams["font.sans-serif"] = ["arial"]
rcParams["font.size"] = 12
fig, ax = pp.subplots()
ax.imshow(hillshade, vmin=0, vmax=255, cmap=cmx.gray)
xlocs, xlabels = pp.xticks()
ylocs, ylabels = pp.yticks()
new_x_labels = np.linspace(
hillshade_header[2], hillshade_header[2] + (hillshade_header[1] * hillshade_header[4]), len(xlocs)
)
new_y_labels = np.linspace(
hillshade_header[3], hillshade_header[3] + (hillshade_header[0] * hillshade_header[4]), len(ylocs)
)
new_x_labels = [str(x).split(".")[0] for x in new_x_labels] # get rid of decimal places in axis ticks
new_y_labels = [str(y).split(".")[0] for y in new_y_labels][::-1] # invert y axis
pp.xticks(xlocs[1:-1], new_x_labels[1:-1], rotation=30) # [1:-1] skips ticks where we have no data
pp.yticks(ylocs[1:-1], new_y_labels[1:-1])
pp.xlabel("Easting (m)")
pp.ylabel("Northing (m)")
# SET UP COLOURMAPS
jet = pp.get_cmap("jet")
m_MIN = np.min(m_values)
m_MAX = np.max(m_values)
cNorm_m_values = colors.Normalize(vmin=m_MIN, vmax=m_MAX)
scalarMap_m_values = cmx.ScalarMappable(norm=cNorm_m_values, cmap=jet)
for i in xrange(len(m_values)):
for j in xrange(len(m_values[0])):
if m_values[i][j] > 0:
colorVal = scalarMap_m_values.to_rgba(m_values[i][j])
pp.scatter(j + corrected_x, i + corrected_y, marker=".", color=colorVal, edgecolors="none")
# Configure final plot
sm = pp.cm.ScalarMappable(cmap=jet, norm=pp.normalize(vmin=m_MIN, vmax=m_MAX))
sm._A = []
cbar = pp.colorbar(sm)
cbar.set_label("M Values")
pp.show()
示例14: make_plots
#.........这里部分代码省略.........
if channel_id[i]==0:
plt.plot(chi[i], m_mean[i], "o", markersize=10, color='black', markeredgecolor = 'black',alpha=0.7)
else:
plt.plot(chi[i], m_mean[i], "o", markersize=8, color=colorVal, markeredgecolor = colorVal,alpha = 0.7)
# plt.plot(chi[i], m_mean[i] + m_standard_error[i], ".", linewidth=0.25, color='k')
# plt.plot(chi[i], m_mean[i] - m_standard_error[i], ".", linewidth=0.25, color='k')
rect1 =plt.Rectangle((21.4577,0), 18.2625, 20, color='red', alpha= 0.1)
rect2 =plt.Rectangle((69.0736,0), 29.3623, 20, color='green', alpha= 0.1)
ax.add_artist(rect1)
ax.add_artist(rect2)
# Configure final plot
ax.spines['top'].set_linewidth(2.5)
ax.spines['left'].set_linewidth(2.5)
ax.spines['right'].set_linewidth(2.5)
ax.spines['bottom'].set_linewidth(2.5)
ax.tick_params(axis='both', width=2.5)
plt.xlabel('$\chi$ (m)', fontsize = axis_size)
plt.ylabel('Gradient in $\chi$ space', fontsize = axis_size)
plt.title('$A_0$: '+str(A_0)+' m$^2$, and $m/n$: '+str(m_over_n), fontsize = label_size)
#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# LONGITUDINAL PROFILES WITH COLOUR SCALE GIVING CHI-m VALUE
plt.figure(3, facecolor='white',figsize=(10,7.5))
ax = plt.subplot(1,1,1)
for i in range (0,len(channel_id)):
colorVal = scalarMap_m_values.to_rgba(m_mean[i])
plt.plot((flow_dist[i]-minfd)/1000, elevation[i], "o", markersize=6, color=colorVal, markeredgecolor = colorVal,alpha = 0.5)
# Configure final plot
sm = plt.cm.ScalarMappable(cmap=hot,norm=plt.normalize(vmin=np.min(m_mean), vmax=np.max(m_mean)))
sm._A = []
cbar = plt.colorbar(sm,orientation='horizontal',use_gridspec=True)
cbar.set_label('Gradient in $\chi$ space', fontsize = axis_size)
plt.xlabel('Distance upstream (km)', fontsize = axis_size)
plt.ylabel('Elevation (m)', fontsize = axis_size)
plt.title('$A_0$: '+str(A_0)+' m$^2$, and $m/n$: '+str(m_over_n), fontsize = label_size)
ax.spines['top'].set_linewidth(2.5)
ax.spines['left'].set_linewidth(2.5)
ax.spines['right'].set_linewidth(2.5)
ax.spines['bottom'].set_linewidth(2.5)
ax.tick_params(axis='both', width=2.5)
cbar.ax.spines['top'].set_linewidth(2.5)
cbar.ax.spines['left'].set_linewidth(2.5)
cbar.ax.spines['right'].set_linewidth(2.5)
cbar.ax.spines['bottom'].set_linewidth(2.5)
cbar.ax.tick_params(axis='both', width=2.5)
plt.tight_layout()
#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# BASIC CHI-PLOT WITH EACH CHANNEL LABELLED WITH A DIFFERENT COLOUR
plt.figure(1, facecolor='white',figsize=(10,7.5))
ax = plt.subplot(1,1,1)
data_pointer = 0 # points to data element in chi and elev vectors
for i in range (0,len(segment_lengths)):
chi_seg = np.zeros(segment_lengths[i])
elev_seg = np.zeros(segment_lengths[i])
示例15: map_dict
def map_dict(export_fn,states_happiness):
# Lambert Conformal map of lower 48 states.
m = Basemap(llcrnrlon=-119,llcrnrlat=22,
urcrnrlon=-64, urcrnrlat=49,
projection='lcc', lat_1=33,lat_2=45,lon_0=-95)
# laod state boundaries.
# data from U.S Census Bureau
# http://www.census.gov/geo/www/cob/st1990.html
shp_info = m.readshapefile('gz_2010_us_040_00_500k/gz_2010_us_040_00_500k','states',drawbounds=False)
# This loads three files:
# gz_2010_us_040_00_500k.dbf
# gz_2010_us_040_00_500k.shp
# gz_2010_us_040_00_500k.shx
max_score = -sys.maxint - 1
min_score = sys.maxint+1
happiest_state = ''
saddest_state = ''
for state in states_happiness:
score = states_happiness[state]
if (score > max_score):
happiest_state = state
max_score = score
if (score < min_score):
saddest_state = state
min_score = score
for state in states_happiness:
states_happiness[state] -= min_score
min_score = 0
max_score = max_score-min_score
# choose a color for each state based on happiness score.
colors={}
statenames=[]
cmap = plt.cm.Blues_r # use 'hot' colormap
vmin = min_score; vmax = max_score # set range.
sm = plt.cm.ScalarMappable(cmap=cmap,
norm=plt.normalize(vmin=vmin, vmax=vmax))
for shapedict in m.states_info:
statename = shapedict['NAME']
#print statesNames[statename], ' ', statename
try:
#score = states_happiness[statesNames[statename]]
score = states_happiness[statename]
except KeyError:
score = 0.0
# calling colormap with value between 0 and 1 returns
# rgba value. Invert color range (hot colors are
# high
# population), take sqrt root to spread out
# colors more.
try:
colors[statename] = cmap((score-vmin)/(vmax-vmin))[:3]
except KeyError:
colors[statename] = cmap(0)[:3]
statenames.append(statename)
# cycle through state names,
# color each one.
for nshape,seg in enumerate(m.states):
xx,yy = zip(*seg)
if statenames[nshape] != 'District of Columbia' and \
statenames[nshape] != "Puerto Rico":
color = rgb2hex(colors[statenames[nshape]])
plt.fill(xx,yy,color,edgecolor='black')
# draw
# meridians
# and
# parallels.
m.drawparallels(np.arange(25,65,20), labels=[0,0,0,0],
zorder=-1,color="w")
m.drawmeridians(np.arange(-120,-40,20),labels=[0,0,0,0],
zorder=-1,color="w")
# set up colorbar:
mm = plt.cm.ScalarMappable(cmap=cmap)
mm.set_array([0,1])
#plt.colorbar(mm, label="Happiness",
# orientation="horizontal", fraction=0.05)
plt.colorbar(mm,orientation="horizontal", fraction=0.05)
#plt.title('Filling State Polygons by Population Density')
plt.gca().axis("off")
plt.savefig(export_fn)
plt.close('all')