简体   繁体   中英

Generating Legend for geopandas plot

I am plotting a shape file with Geopandas. Additionally im Adding Points of a dataframe (see picture). Now im trying to add a legend (at the right of the original plot) for the point. I dont really know how to do that!

Plot

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import geopandas as gpd
import test

variable = 'RTD_rtd'

df = test.getdataframe()
gdf = gpd.GeoDataFrame(
    df, geometry=gpd.points_from_xy(df.NP_LongDegree, df.NP_LatDegree))


fp = "xxx"
map_df = gpd.read_file(fp)
ax = map_df.plot(color='white', edgecolor='black', linewidth=0.4, figsize= (10,10))

gdf.plot(column=variable, ax=ax, cmap='Reds', markersize=14.0, linewidth=2.0)
plt.show()

One Idea was to add a simple legend. I want something looking better. Maybe something similar to whats done in this tutorial: Tutorial

I followed the example that you referred to and this is the concise version. It would have been better if you could have shared a bit of your dataset 'df'. It seems that you want to have a colorbar which fig.colorbar generates.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import geopandas as gpd
import test
from shapely.geometry import Point

df = pd.read_csv('london-borough-profiles.csv', header=0)
df = df[['Area name','Population density (per hectare) 2017']]

fp = 'London_Borough_Excluding_MHW.shp'
map_df = gpd.read_file(fp)
gdf = map_df.set_index('NAME').join(df.set_index('Area name'))

variable = 'Population density (per hectare) 2017'
vmin, vmax = 120, 220
fig, ax = plt.subplots(1, figsize=(10, 6))
gdf.plot(column=variable, cmap='Blues', ax = ax, linewidth=0.8, edgecolor='0.8')
ax.axis('off')
ax.set_title('Population density (per hectare) 2017', fontdict={'fontsize': '25', 'fontweight' : '3'})
ax.annotate('Source: London Datastore, 2014',xy=(0.1, .08),  xycoords='figure fraction', horizontalalignment='left', verticalalignment='top', fontsize=12, color='#555555')
sm = plt.cm.ScalarMappable(cmap='Blues', norm=plt.Normalize(vmin=vmin, vmax=vmax))
sm._A = []
cbar = fig.colorbar(sm)

输出量

您可以将其添加到解决方案中,为此必须为每个图设置标签

plt.legend()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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