3

In matplotlib how to overlay the shapefile (available in folder) as attached below at the top right position outside the plot.enter image description here

2964502
  • 4,301
  • 12
  • 35
  • 55
  • 1
    Perhaps you could use figimage, as described [here][1]. [1]: http://stackoverflow.com/questions/3609585/how-to-insert-a-small-image-on-the-corner-of-a-plot-with-matplotlib – banderkat Dec 28 '13 at 03:43
  • Any luck with the answers provided? – JSuar Jan 01 '14 at 17:46
  • @JSuar thanks for your answer, sorry for my late response. i could not come here before bounty expires, will award you new bounty. – 2964502 Jan 02 '14 at 06:02
  • @viena did you add another bounty to this question? Are you still having issues with the problem? – JSuar Jan 06 '14 at 14:01
  • @JSuar this is just to award you since my previous bounty with 50 points lost when i could not check stackoverflow with in bounty grace period – 2964502 Jan 08 '14 at 05:21
  • @viena I appreciate that. For future reference, you can award a bounty to an answer directly. No need to reassign a bounty to the question. See: [Can I award a bounty to an old answer?](http://meta.stackexchange.com/questions/16065/how-does-the-bounty-system-work) – JSuar Jan 08 '14 at 13:01

2 Answers2

4

The code referenced by banderkat:

import matplotlib.pyplot as plt
import Image
import numpy as np

im = Image.open('Jbc4j.jpg')
width = im.size[0]
height = im.size[1]

# We need a float array between 0-1, rather than
# a uint8 array between 0-255
im = np.array(im).astype(np.float) / 255

a = np.random.randint(0,100,100)
b = range(100)
fig = plt.figure(1,figsize=(5, 7), dpi=80, facecolor='w')
ax = fig.add_subplot(111)
ax.scatter(a,b)
fig.canvas.draw()

# With newer (1.0) versions of matplotlib, you can 
# use the "zorder" kwarg to make the image overlay
# the plot, rather than hide behind it... (e.g. zorder=10)
fig.figimage(im, fig.bbox.xmax - width, fig.bbox.ymax - height, zorder=0)

# (Saving with the same dpi as the screen default to
#  avoid displacing the logo image)
fig.savefig('temp.png', dpi=80)

plt.show()

Produces the following result (imaged cropped to save space).

zorder = 0

Changing the zorder=1 will place the image on top.

zorder = 1

Other helpful references:

Community
  • 1
  • 1
JSuar
  • 21,056
  • 4
  • 39
  • 83
3

You can use basemap toolkit to load and plot shapefile. Here I've plotted shapeFile in a separate axes and aligned it to top-right of other axes plot using 'subplot2grid'.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import matplotlib.gridspec as gridspec


def plotShapeFile():
    # Lambert Conformal Conic map.
    m = Basemap(llcrnrlon=-100.,llcrnrlat=0.,urcrnrlon=-20.,urcrnrlat=57.,
                projection='lcc',lat_1=20.,lat_2=40.,lon_0=-60.,
                resolution ='l',area_thresh=1000.)
    # read shapefile.
    shp_info = m.readshapefile('C:/basemap-1.0.6/basemap-1.0.6/examples/huralll020','hurrtracks',drawbounds=False)
    # find names of storms that reached Cat 4.
    names = []
    for shapedict in m.hurrtracks_info:
        cat = shapedict['CATEGORY']
        name = shapedict['NAME']
        if cat in ['H4','H5'] and name not in names:
            # only use named storms.
            if name != 'NOT NAMED':  names.append(name)

    # plot tracks of those storms.
    for shapedict,shape in zip(m.hurrtracks_info,m.hurrtracks):
        name = shapedict['NAME']
        cat = shapedict['CATEGORY']
        if name in names:
            xx,yy = zip(*shape)
            # show part of track where storm > Cat 4 as thick red.
            if cat in ['H4','H5']:
                m.plot(xx,yy,linewidth=1.5,color='r')
            elif cat in ['H1','H2','H3']:
                m.plot(xx,yy,color='k')

    # draw coastlines, meridians and parallels.
    m.drawcoastlines()
    m.drawcountries()
    m.drawmapboundary(fill_color='#99ffff')
    m.fillcontinents(color='#cc9966',lake_color='#99ffff')
    m.drawparallels(np.arange(10,70,20),labels=[1,1,0,0])
    m.drawmeridians(np.arange(-100,0,20),labels=[0,0,0,1])




if __name__ == '__main__':
    fig=plt.figure()
    plt.subplots_adjust(wspace=0.001, hspace=0.001)

    ax1=plt.subplot2grid((5,5), (0,0), colspan=4, rowspan=4)
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    fracs = [15,30,45, 10]
    explode=(0, 0.05, 0, 0)
    p1,t1,at1 = plt.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
    plt.title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})

    ax2=plt.subplot2grid((5,5), (0,4), colspan=1, rowspan=1)
    #draw shapeFile on the current active axes, i.e. ax2
    plotShapeFile()

    plt.tight_layout()
    plt.show()

Below are links to references I've used:

http://sourceforge.net/projects/matplotlib/files/matplotlib-toolkits/basemap-1.0.6/ http://matplotlib.org/basemap/users/examples.html

Output:

enter image description here

neon
  • 462
  • 6
  • 17