How to fix KeyError: 'PROJ_LIB' while using basemap in python ?

Published: December 18, 2020

Tags: Python; Basemap;

DMCA.com Protection Status

Lets try the following example with matplotlib. (Note: check first if basemap is installed by entering "import basemap" in the python interpreter. if not just try conda install -c anaconda basemap or pip install basemap)

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

fig = plt.figure()


m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90, 
                llcrnrlon=-180,urcrnrlon=180,resolution='c')

m.drawcoastlines()
m.fillcontinents()
m.drawparallels(np.arange(-90,90,30),labels=[1,1,0,1], fontsize=8)
m.drawmeridians(np.arange(-180,180,30),labels=[1,1,0,1], rotation=45, fontsize=8)

plt.title('How to add a title on x and y-axis using Basemap ?', fontsize=8)

plt.xlabel('Longitude', labelpad=40, fontsize=8)
plt.ylabel('Latitude', labelpad=40, fontsize=8)

plt.savefig('plot_world_map_using_matplotlib_02.png', bbox_inches='tight')

if you get the error message

KeyError: 'PROJ_LIB'

just add the following lines in your python script (you need first to find the full path to "/share/proj", for example here It was located under anaconda3 and installed in an environment called 'worklab'):

import os

os.environ['PROJ_LIB'] = '/Users/mb/anaconda3/envs/worklab/share/proj'

(replace '/Users/mb/anaconda3/envs/worklab/share/proj' by your path to /share/proj). To do that you can for example just enter the command

which python

to get the path to python, for example

/Users/mb/anaconda3/bin/python

Now you should be able to plot a map using basemap

from mpl_toolkits.basemap import Basemap
import numpy as np

import matplotlib.pyplot as plt
import os

os.environ['PROJ_LIB'] = '/Users/mb/anaconda3/envs/worklab/share/proj'

fig = plt.figure()


m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90, 
                llcrnrlon=-180,urcrnrlon=180,resolution='c')

m.drawcoastlines()
m.fillcontinents()
m.drawparallels(np.arange(-90,90,30),labels=[1,1,0,1], fontsize=8)
m.drawmeridians(np.arange(-180,180,30),labels=[1,1,0,1], rotation=45, fontsize=8)

plt.title('How to add a title on x and y-axis using Basemap ?', fontsize=8)

plt.xlabel('Longitude', labelpad=40, fontsize=8)
plt.ylabel('Latitude', labelpad=40, fontsize=8)

plt.savefig('plot_world_map_using_matplotlib_02.png', bbox_inches='tight')

How to fix KeyError: 'PROJ_LIB' while using basemap in python ?
How to fix KeyError: 'PROJ_LIB' while using basemap in python ?

Image

of