Han Zhengzu Han Zhengzu - 3 months ago 17x
Python Question

How to draw contourf plot for a particular shape in Python-Matplotlib-Basemap

For example, I have a 3-D array data represent the chemical concentration among the area shown like:

And I want to plot it just in some administrative division(not a square) that belong to this domain.

Now I can read and plot shapefile in Basemap, but I can't find a way to draw some elements beyond it?

If it's possible, How to make the figure size smaller? Because when I add shapefile in basemap, the output file is way larger.

Wish for your reply! Thanks!


I have done something similar for plotting trace-gas concentrations within counties within the US, which I think is very similar to what you are trying to do.

import pandas as pd, numpy as np, datetime as dt, pytz
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from mpl_toolkits.basemap import Basemap
from os import getcwd, chdir
from pylab import *

# create figure
    fig = figure( figsize=(6.25,4.5) )
    ax  = fig.add_subplot(111)

    m = Basemap(projection='cyl', llcrnrlat=minlat, urcrnrlat=maxlat, llcrnrlon=minlon, urcrnrlon=maxlon, resolution='i')

    lw = 0.1
    m.drawparallels(np.arange(30, 50, 2), labels=[1,0,0,1], fontsize=6, labelstyle='', rotation=0, linewidth=0.25)
    m.drawmeridians(np.arange(-86,-70,2), labels=[1,0,0,1], fontsize=6, labelstyle='', rotation=45, linewidth=0.25)

    ax2 = gca()

    a = np.ones( (10,10) )
    b = a*10
    cb = ax.scatter(x=a, y=a, s=1, c=b, vmin=0, vmax=10)   # create dummy plot to allow colorbar insertion

    # insert colorbar
    axins = inset_axes(ax,
                   width="5%", # width = 10% of parent_bbox width
                   height="100%", # height : 50%
                   bbox_to_anchor=(1.05, 0., 1, 1),
    cbar = colorbar(cb, cax=axins)
    cbar.set_label('NO\$\mathrm{_2}$ (ppb)', fontsize=8)

# fill in counties
# I think this is the part you are most interested in
county_mean = county_data.mean()

# since I want to color within the map to match a specific color 
# within the cbar, I define it here based on the cbar's color coding
if pd.isnull(county_mean.no2)[0]:
    color = (1,1,1)
    color = cbar.to_rgba(county_mean.no2[0])

# get the polygon values that define the county boundaries
# here, "r" represents the county PID (identifier)
poly = Polygon(m.counties[r], facecolor=color, edgecolor='k')

This is a general outline for how you can do this. With some modifications I think you will be on your way.