Search code examples
pandasmatplotlibcartopy

How to scatter plot values in a range color with cartopy?


I have this df:

     STATION LONGITUDE  LATITUDE  TMAXPERC
0    000130 -80.45750  -3.81333   9.034495
1    000132 -80.45722  -3.50833   7.291477
2    000134 -80.23722  -3.57611  15.760175
3    000135 -80.32194  -3.44056   5.256434
4    000136 -80.66083  -3.94889  12.301515
..      ...       ...       ...        ...
366  158323 -69.99972 -17.55917  57.318854
367  158325 -69.94889 -17.66083  87.762365
368  158326 -69.74556 -17.18639  40.719109
369  158327 -69.81306 -17.23722  86.950173
370  158328 -69.77944 -17.52500  53.413032

[371 rows x 4 columns]

I'm making a scatter plot with latitude and longitude with this code.

import cartopy.crs as ccrs
import pandas as pd
import cartopy
%matplotlib inline
import numpy as np
import cartopy.io.img_tiles as cimgt
import cartopy.io.shapereader as shpreader
import cartopy.feature as cfeature
import matplotlib.pyplot as plt

data = pd.ExcelFile("path/filename.xlsx")
df =pd.read_excel(data,'Hoja1',dtype={'STATION': str})
df=df[['STATION','LONGITUDE','LATITUDE','TMAXPERC']]

reader = shpreader.Reader('C:/Ubuntu/Python/Shapefile/Dz/direcciones.shp')
counties = list(reader.geometries())
COUNTIES = cfeature.ShapelyFeature(counties, ccrs.PlateCarree())

plt.figure(figsize=(15,15))
stamen_terrain = cimgt.Stamen('terrain-background')
m10 = plt.axes(projection=stamen_terrain.crs)
plt.scatter(
    x=df["LONGITUDE"],
    y=df["LATITUDE"],
    color="red",
    s=4,
    alpha=1,
    transform=ccrs.PlateCarree()
)
# (x0, x1, y0, y1)
m10.set_extent([-85, -65, 2, -20], ccrs.PlateCarree())         
# add map, zoom level
m10.add_image(stamen_terrain, 8)
m10.add_feature(COUNTIES, facecolor='none', edgecolor='black')
m10.legend()
m10.gridlines()
plt.show()

And this is the result: enter image description here

But i want to make a scatter plot with df['TMAXPERC']. I want to plot dots in the map with scalecolor based on the TMAXPERC values in their corresponding latitude and longitude. How can i do this? Thanks in advance.


Solution

  • You need to specify some options properly:

    plt.scatter(
        x=df["LONGITUDE"],
        y=df["LATITUDE"],
        c=df["TMAXPERC"], cmap='viridis',  #this is the changes
        s=4,
        alpha=1,
        transform=ccrs.PlateCarree()
    )