繁体   English   中英

Matplotlib 和 Cartopy - 如何根据分类列自动使用 colors 自动 plot 数据?

[英]Matplotlib & Cartopy - How to automatically plot data with colors depending on a categorical column?

我正在尝试 plot 在 Cartopy 中运送轨迹,但无法自动使用我的 df 列来设置数据的颜色组。

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()

这会引发错误“dtype:object 不是颜色的有效值”。 在 Geopandas 中,您可以使用“列”字段设置颜色组。 Matplotlib/Cartopy 有类似的东西吗?

提前感谢您提供的任何帮助!

您可以将ax.scatter与指向 integer 的 DataFrame 列的c关键字参数一起使用。 如果您需要将文本转换为 integer label,可以使用sklearn.preprocessing.LabelEncoder轻松完成。

以下是使用您的 map 实例的示例:

# 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())

具有相同“大陆”label 的点具有相同的 integer label code和颜色。

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM