在 Geopandas 中自定义图例标签

lsr*_*729 2 python matplotlib legend geopandas

我想自定义 geopandas 图例上的标签。

fig, ax = plt.subplots(figsize = (8,5))

gdf.plot(column = "WF_CEREAL", ax = ax, legend=True, categorical=True, cmap='YlOrBr',legend_kwds = {"loc":"lower right"}, figsize =(10,6))

Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

添加"labels"legend_kwds没有帮助。

我尝试通过以下方式添加标签legend_kwds,但没有成功-

legend_kwds = {"loc":"lower right", "labels":["low", "mid", "high", "strong", "severe"]

legend_labels:["low", "mid", "high", "strong", "severe"]

legend_labels=["low", "mid", "high", "strong", "severe"]

swa*_*hai 5

由于该问题没有可重复的代码和数据可供处理。我会用最好的方式给出一个演示代码,一般读者可以遵循,其中一些可以回答问题。

我在下面提供的代码可以在不需要外部数据的情况下运行。在不同的地方插入注释来解释重要的步骤。

# Part 1
# Classifying the data of choice

import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
world['gdp_per_cap'] = world.gdp_md_est / world.pop_est

num_classes = 4   #quartile scheme has 4 classes

# You can use values derived from your preferred classification scheme here
num_qtiles = [0, .25, .5, .75, 1.]   #class boundaries for quartiles
# Here is the categorical data to append to the dataframe
# They are also used as legend's label texts
qlabels = ["1st quartile","2nd quartile","3rd quartile","4th quartile"]  #matching categorical data/labels

# Conditions
# len(num_qtiles)-1 == num_classes
# len(qlabels) == num_classes

# Create a new column for the categorical data mentioned above
world['gdp_quartile'] = pd.qcut(world['gdp_per_cap'], num_qtiles, labels=qlabels)

# Plotting the categorical data for checking
ax1 = world['gdp_quartile'].value_counts().plot(figsize=(5,4), kind='bar', xlabel='Quartile_Classes', ylabel='Countries', rot=45, legend=True)
Run Code Online (Sandbox Code Playgroud)

第 1 部分的输出:-

条形图1

# Part 2
# Plot world map using the categorical data

fig, ax = plt.subplots(figsize=(9,4))

# num_classes = 4 # already defined
#color_steps = plt.colormaps['Reds']._resample(num_classes)   #For older version
color_steps = plt.colormaps['Reds'].resampled(num_classes)    #Current version of matplotlib

# This plots choropleth map using categorical data as the theme
world.plot(column='gdp_quartile', cmap = color_steps, 
           legend=True, 
           legend_kwds={'loc':'lower left', 
                        'bbox_to_anchor':(0, .2), 
                        'markerscale':1.29, 
                        'title_fontsize':'medium', 
                        'fontsize':'small'}, 
           ax=ax)

leg1 = ax.get_legend()
leg1.set_title("GDP per capita")
ax.title.set_text("World Map: GDP per Capita")
plt.show()
Run Code Online (Sandbox Code Playgroud)

第 2 部分的输出:-

地图猫

编辑

附加代码,用它来替换上面的行plt.show()。这回答了下面评论中提出的问题。

# Part 3
# New categorical texts to use with legend
new_legtxt = ["low","mid","high","v.high"]
for ix,eb in enumerate(leg1.get_texts()):
    print(eb.get_text(), "-->", new_legtxt[ix])
    eb.set_text(new_legtxt[ix])

plt.show()
Run Code Online (Sandbox Code Playgroud)