I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error:
KeyError: 'PROJ_LIB'
After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as all other relevant libraries), I have activated the environment. But when importing Basemap I still receive the same KeyError.
Here's what I did in my MacOS terminal:
conda create --name Py3.6 python=3.6 basemap
source activate Py3.6
conda upgrade proj4
env | grep -i proj
conda update --channel conda-forge proj4
Then in Jupyter Notebook I run the following:
from mpl_toolkits.basemap import Basemap
Can anyone tell me why this results in a KeyError?
Need to set the PROJ_LIB environment variable either before starting your notebook or in python with os.environ['PROJ_LIB'] = '<path_to_anaconda>/share/proj'
Ref. Basemap import error in PyCharm —— KeyError: 'PROJ_LIB'
In Windows 10 command line: first find the directory where the epsg file is stored:
where /r "c:\Users\username" epsg.*
...
c:\Users\username\AppData\Local\conda\conda\envs\envname\Library\share\epsg
...
then either in command line:
activate envname
SET PROJ_LIB=c:\Users\username\AppData\Local\conda\conda\envs\envname\Library\share
(make sure there are no leading on trailing spaces in the path!) and then
jupyter notebook
or add this to your jupyter notebook (as suggested by john ed):
import os
os.environ['PROJ_LIB'] = r'c:\Users\username\AppData\Local\conda\conda\envs\envname\Library\share'
The problem occurs as the file location of "epsg" and PROJ_LIB has been changed for recent versions of python, but somehow they forgot to update the init.py for Basemap. If you have installed python using anaconda, this is a possible location for your espg file:
C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\pkgs\proj4-5.1.0-hfa6e2cd_1\Library\share
So you have to add this path at the start of your code in spyder or whatever field you are using.
import os
os.environ['PROJ_LIB'] = r'C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\pkgs\proj4-5.1.0-hfa6e2cd_1\Library\share'
from mpl_toolkits.basemap import Basemap
If you can not locate epsg file at all, you can download it here:
https://raw.githubusercontent.com/matplotlib/basemap/master/lib/mpl_toolkits/basemap/data/epsg
And copy this file to your PATH, e.g. to:
os.environ['PROJ_LIB'] = 'C:\Users\username\Anaconda3\pkgs\basemap-1.2.0-py37h4e5d7af_0\Lib\site-packages\mpl_toolkits\basemap\data\'
This is the ONLY solution that worked for me on Windows 10 / Anaconda 3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With