为大 pandas 图生成图例 [英] Generating Legend for geopandas plot

查看:70
本文介绍了为大 pandas 图生成图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Geopandas绘制形状文件.另外,im正在添加数据帧的点(请参见图片).现在,我正在尝试为该点添加图例(在原始图的右侧).我真的不知道该怎么做!

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)

这篇关于为大 pandas 图生成图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆