我正在尝试绘制加利福尼亚州代表错过选票的百分比,但要注意根据政党进行着色。我可以在同一个图上使用 GeoPandas 绘制两个颜色图,但我无法在图例上显示两个颜色图。
fig, ax = plt.subplots(figsize=(10, 6))
california = merged[merged['STATENAME'] == 'California']
rs = california[california['party'] == 'R']
ds = california[california['party'] == 'D']
# set the value column that will be visualised
variable = 'PCT'
# create map
rs.plot(column=variable, ax=ax, legend=False, cmap='Reds', scheme='quantiles', k=7)
ds.plot(column=variable, ax=ax, legend=True, cmap='Blues', scheme='quantiles', k=7)
结果图如下所示:
关键是确保您拥有对两个图例对象的引用:
在您的示例中,您实例化的第一个实例(并显示了),您没有实例化的第二个实例(未显示)。
一般来说,这意味着:
# Add first legend: only labeled data is included
leg1 = ax.legend(loc='upper right')
# Add second legend
# leg1 will be removed from figure
leg2 = ax.legend(loc='lower left')
# Manually add the first legend back
ax.add_artist(leg1)
ByTheWay:您的代码示例不完整:缺少导入和到 GeoDataFrame 的转换。
以下内容应该有效。您需要使用
ax.get_legend
而不是 ax.legend
,如《squeequer44》建议的那样:
fig, ax = plt.subplots(figsize=(10, 6))
california = merged[merged['STATENAME'] == 'California']
rs = california[california['party'] == 'R']
ds = california[california['party'] == 'D']
# set the value column that will be visualised
variable = 'PCT'
# create map
rs.plot(column=variable, ax=ax, legend=False, cmap='Reds', scheme='quantiles', k=7)
leg1 = ax.get_legend() # save the legend from the first plot
ds.plot(column=variable, ax=ax, legend=True, cmap='Blues', scheme='quantiles', k=7)
ax.add_artist(leg1) # add the first legend back in
请参阅此处了解完整的最小工作示例。