Application of Python for preparing Base Maps

Application of Python for preparing base maps

One of the most versatile and potent programming languages today is Python. For your study on shooting fatalities, a peer reviewer asked for a beautiful basemap of Philadelphia that depicted the connections between hospitals and major thoroughfares.

As a result, if you are a crime analyst working for a particular city, it can make sense to get the original vector data for streets and highways and design your maps in your unique style.


However, that requires a bit of work, so these basemaps are fantastic for a more comprehensive solution. Here you need to hire Python programmer when you are preparing a new basemap. Here are a few lists about the Application of Python for preparing basemaps:

The front matter

First, you have always had trouble using the many geo tools in Python on your Windows computer. Most recently, you have had a problem with older versions of the pyproj and epsg programs.

You made your conda environment for geospatial purposes on the people’s advice, which has been successful thus far. As non-traditional libraries, you require geopandas, pyproj, and contexily. Then you need to switch your working directory to the location of your data before updating your matplotlib defaults.


Python script to make a basemap

For Philadelphia


Import geopandas

Import pyproj

Import contextily as cx

Import matplotlib

Import matplotlib.pyplot as plt

Import os


#Plot theme

andy_theme = {‘axes.grid’: True,

‘ ‘–‘,

 ‘legend.framealpha’: 1,

‘legend.facecolor’: ‘white’,

‘legend.shadow’: True,

‘legend.fontsize’: 14,

‘legend.title_fontsize’: 16,

‘xtick.labelsize’: 14,

‘ytick.labelsize’: 14,

‘axes.labelsize’: 16,

 ‘axes.titlesize’: 20,

 ‘figure.dpi’: 100}

Developing the basemap

Now you are in the important part. Here, you need to generate a foundation matplotlib plot object with the Philly border outline using the default charting methods from the geopandas boundary plot. Then disable the tick markings.

You will then use some rudimentary code to create the north arrow and scale bar. The north arrow uses arrows and annotations, so it only depends on the plot’s north-up orientation. This needs to be adjusted for your map if it is not.

The scale bar is simpler to plot on the matplotlib plot, and you plot a rectangle and then insert text in the center of the bar. And you simply create a rectangle 5 kilometers long because the projected units are in meters.

Now include the locations of the hospitals. Please take note that you labeled both the hospitals and the outline. This is required to save those objects into the Matplotlib legend, which you need to incorporate into the plot and raise the default size.

Given that you pass in the basemap’s coordinate reference system, the contextily add basemap method does everything for me without my intervention. Then you save the file as a PNG with lesser resolution.

#now making a basemap in contextily

Ax = ph_gp.boundary.plot(color=’k’, linewidth=3, figsize=(12,12), label=’City Boundary’, edgecolor=’k’)

#ax.set_axis_off() #I still want a black frame around the plot



#add a north arrow,

X, y, arrow_length = 0.85, 0.10, 0.07

ax.annotate(‘N’, xy=(x, y), xytext=(x, y-arrow_length),

arrowprops=dict(facecolor=’black’, width=5, headwidth=15),

 ha=’center’, va=’center’, fontsize=20, xycoords=ax.transAxes)

#add scale-bar

X, y, scale_len = 829000, 62500, 5000 #arrowstyle=’-‘

scale_rect=matplotlib.patches.Rectangle((x,y),scale_len, 200,linewidth=1,edgecolor=’k’,facecolor=’k’)


plt.text(x+scale_len/2, y+400, s=’5 KM’, fontsize=15, horizontalalignment=’center’)

#Add in hospitals as points

plt.scatter(hx, hy, s=200, c=”r”, alpha=0.5, label=’Trauma Hospitals’)

#now making a nice legend

ax.legend(loc=’upper left’, prop={‘size’: 20})

#now adding in the basemap imagery

cx.add_basemap(ax,,source=cx.providers.CartoDB.Voyager, zoom=12)

#now exporting the map to a PNG file

plt.savefig(‘PhillyBasemap_LowerRes.png’, dpi=100) #bbox_inches=’tight’

Calculating zoom levels

To find the setting that best suits the thematic information you are overlaying on your map, experiment with the DPI, zoom levels and background tile server. Here are some useful functions for seeing the default zoom level, how many additional map tiles need to be downloaded when the default zoom level is increased, and a list of available tile providers.

#identifying how many tiles

latlon_outline = ph_gp.to_crs(‘epsg:4326’).total_bounds

def_zoom = cx.tile._calculate_zoom(*latlon_outline)

print(f’Default Zoom level {def_zoom}’)

cx.howmany(*latlon_outline, def_zoom, ll=True)

cx.howmany(*latlon_outline, def_zoom+1, ll=True)

cx.howmany(*latlon_outline, def_zoom+2, ll=True)

#checking out some of the other providers and tiles

Print ( cx.providers.CartoDB.Voyager )

Print ( cx.providers.Stamen.TonerLite )

Print ( cx.providers.Stamen.keys() )

A projected map

When utilizing maps, choosing the projection is the first thing to do. You’re probably aware of the notion that a spherical map, like the one of the Earth, cannot be projected onto a flat surface without being altered or losing continuity.

There are several options for these projections, which have been created throughout human history. Depending on the map projection’s intended application, some map attributes are helpful.

Many of these projections are implemented by the Basemap package, and a short format code refers to each. Here, you will quickly go through a few of the most popular ones. To begin, let’s define a handy method for drawing the longitude and latitude lines:

From itertools import chain

def draw_map(m, scale=0.2):

# draws a shaded-relief image


# lats and longs are returned as a dictionary

lats = m.drawparallels(np.linspace(-90, 90, 13))

lons = m.drawmeridians(np.linspace(-180, 180, 13))

# Keys contain the plt.Line2D instances

lat_lines = chain(*(tup[1][0] for tup in lats.items()))

lon_lines = chain (*(tup[1][0] for tup in lons.items()))

all_lines = chain (lat_lines, lon_lines)

# cycle through these lines and set the desired style

for line in all_lines:

line.set(linestyle=’-‘, alpha=0.3, color=’w’)

Conic projections

The map is projected through a conic projection onto a single cone, which is then unfolded. Local properties may be excellent, while locations far from the cone’s focus point may experience significant distortion.

The map is projected onto a cone with an arrangement that ensures the distances between two standard parallels are accurately depicted, with size rising outside and decreasing between them.

 The equal-area and the equidistant conic projections are two additional helpful conic projections.

Conic projections are frequently suitable for depicting small to medium areas of the globe, much like perspective projections.

Fig = plt.figure(figsize=(8, 8))

m = Basemap(projection=’lcc’, resolution=None,

lon_0=0, lat_0=50, lat_1=45, lat_2=55,

Width=1.6E7, height=1.2E7)


Cylindrical projections

Cylindrical projections are the most detailed map projections, converting lines of constant latitude and longitude to horizontal and vertical lines, respectively. This mapping accurately depicts equatorial regions but produces severe distortions close to the poles. Various cylindrical projections have differing latitude line spacings, which results in different conservation laws and a distortion towards the poles. The equidistant cylindrical projection, which selects a latitude scale that retains distances between meridians, is demonstrated in the accompanying picture. The equal cylindrical area (cea) and Mercator (projection=’merc’) projections are additional cylindrical projections.

m = Basemap(projection=’cyl’, resolution=None,

llcrnrlat=-90, urcrnrlat=90,

llcrnrlon=-180, urcrnrlon=180, )


The extra arguments to Basemap for this view define, in degrees, the latitude (llcrnr) and longitude (lon) of the desired map’s lower-left and upper-right corners, respectively.

Other projection

If you are going to work with maps a lot, you need to read about many projections out there and learn about their characteristics, benefits, and drawbacks. They most likely come with the Basemap package. If you delve far enough into this subject, you will discover a fantastic geo-viz geek subculture willing to defend their preferred projection for any particular application passionately.

Data Plotting on Maps

The Basemap’s ability to overlay several types of data onto a map background may be its most practical feature. Any plt function will work on the map for basic plotting and text, and you can use the Basemap instance to project latitude and longitude coordinates to (x, y) coordinates for plt plotting.

Numerous more map-specific operations are also accessible as Basemap instance methods. The only difference between these and their conventional Matplotlib counterparts is that they feature a second Boolean parameter called latlon, which, when set to True, enables you to supply the method raw latitudes and longitudes rather than projected (x, y) coordinates.

Some of these map-specific techniques are:

Contour ()/contourf() : Draw contour lines or filled contours

imshow(): Draw an image

pcolor()/pcolormesh() : Draw a pseudocolor plot for irregular/regular meshes

Plot (): Draw lines and markers.

Scatter (): Draw points with markers.

Quiver (): Draw vectors.

Barbs (): Draw wind barbs.

Drawgreatcircle (): Draw a great circle.

The final steps to follow

You now have some practical experience utilizing one of the most well-known Javascript online mapping libraries and geocoding using standard Python data analysis modules.

There are other plugins you may test out if you want to use to investigate extra online mapping features. The ability to perform heat mapping and build time-based visualizations may be particularly relevant.

Wrapping it up

Finally, the above-explained guide helps you to prepare basemaps. Plot the data in a range of different map projections using the list of projections that Basemap supports and the usage instructions explained above.

Author Bio:

Maulik Shah is the CEO of BiztechCS, a development company. He often takes the front seat in the company’s development projects, because he enjoys solving problems through technology. When it comes to writing for any blog, his contribution is priceless. Maulik ensures that his interaction with development is frequent enough, and his industry knowledge ever evolving, that he can share it. Despite his packed days, Maulik’s door is always open and he is generous with sharing this knowledge and experience.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *