从Matplotlib图例中排除Cartopy元素

时间:2019-06-28 17:08:22

标签: python matplotlib cartopy

尽管插入了label='_nolegend_',但我正在将散点图绘制到地图上并在图例中看到不需要的矩形:

# import functions
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.io.img_tiles as cimgt

# Create a Stamen terrain background instance
stamen_terrain = cimgt.Stamen('terrain-background')
fig = plt.figure(figsize = (10,10))
ax = fig.add_subplot(1, 1, 1, projection=stamen_terrain.crs, label='_nolegend_')

# Set range of map, stipulate zoom level
ax.set_extent([-122.7, -121.5, 37.15, 38.15], crs=ccrs.Geodetic())
ax.add_image(stamen_terrain, 12, label='_nolegend_')

# Add scatter point
ax.scatter(-122.4194, 37.7749, s=55, c='k', transform=ccrs.PlateCarree())    
ax.legend(('','','San Francisco'), loc = 3)
plt.show()

如何删除矩形,仅在图例中显示散点?

Legend has unwanted rectangles

1 个答案:

答案 0 :(得分:1)

问题是您通过('','','San Francisco')为轴中的每个元素设置了标签。相反,只需将标签设置为散点图本身

ax.scatter(..., label="Some City")
ax.legend(loc=3)

或者,如果您不想给散布标签,可以将句柄和标签传递到legend

sc = ax.scatter(...)    
ax.legend(handles=[sc], labels=['Some City'], loc = 3)