[英]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.我正在尝试 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()
This throws the error 'dtype: object is not a valid value for color'.这会引发错误“dtype:object 不是颜色的有效值”。 In Geopandas you can set the color groups using the 'column' field.
在 Geopandas 中,您可以使用“列”字段设置颜色组。 Is there anything similar for Matplotlib/Cartopy?
Matplotlib/Cartopy 有类似的东西吗?
Thanks in advance for any help provided!提前感谢您提供的任何帮助!
You can use ax.scatter
with the c
keyword argument pointing to a DataFrame column of integer.您可以将
ax.scatter
与指向 integer 的 DataFrame 列的c
关键字参数一起使用。 If you need to convert text to a integer label, it can be done easily with the sklearn.preprocessing.LabelEncoder
.如果您需要将文本转换为 integer label,可以使用
sklearn.preprocessing.LabelEncoder
轻松完成。
Here is an example using your map instance:以下是使用您的 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())
The points with the same 'Continent' label have the same integer label code
and color.具有相同“大陆”label 的点具有相同的 integer label
code
和颜色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.