Skip to content
Advertisement

Matplotlib & Cartopy – How to automatically plot data with colors depending on a categorical column?

I am trying to plot ship trajectories in Cartopy, but am unable to automatically use a column of my df to set the color groups of the data.

import cartopy.feature as cf
import cartopy.crs as ccrs
import matplotlib as mpl

mpl.rcParams['agg.path.chunksize'] = 10000

proj = ccrs.AlbersEqualArea(central_longitude=-0,
                            central_latitude=35,
                            standard_parallels=(0, 80))

map = plt.figure(figsize=(30,30))
ax = plt.axes(projection=proj)
ax.set_extent([-10.37109375, 42.275390625, 29.458731185355344, 46.13417004624326], crs=ccrs.PlateCarree())
ax.coastlines(resolution='10m')

ax.add_feature(cf.LAND)
ax.add_feature(cf.OCEAN)
ax.add_feature(cf.COASTLINE)
ax.add_feature(cf.BORDERS, linestyle=':')
ax.add_feature(cf.LAKES, alpha=0.5)
ax.add_feature(cf.RIVERS)

ax.plot(df_vessels['LON'], df_vessels['LAT'], 'ro', color=df_vessels['DepPort'], transform=ccrs.PlateCarree())

ax.stock_img()

This throws the error ‘dtype: object is not a valid value for color’. In Geopandas you can set the color groups using the ‘column’ field. Is there anything similar for Matplotlib/Cartopy?

Thanks in advance for any help provided!

Advertisement

Answer

You can use ax.scatter with the c keyword argument pointing to a DataFrame column of integer. If you need to convert text to a integer label, it can be done easily with the sklearn.preprocessing.LabelEncoder.

Here is an example using your map instance:

# Example dataframe

df = pd.DataFrame()
df['Name'] = ['Marseille', 'Tunis', 'Athens']
df['lon'] = [5.3698, 9.5375, 23.7275]
df['lat'] = [43.2965, 33.8869, 37.9838]
df['Continent'] = ['Europe', 'Africa', 'Europe']

# Encoding label
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
code = le.fit_transform(df['Continent'])
ax.scatter(df['lon'], df['lat'], marker='*', s=500, c=code, cmap='jet', transform=ccrs.PlateCarree())

The points with the same ‘Continent’ label have the same integer label code and color.

enter image description here

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement