在 Geopandas 中自定义图例标签

问题描述 投票:0回答:3

我想自定义 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))

"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"]

python matplotlib legend geopandas
3个回答
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)

第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()

第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()

0
投票

我不确定这是否有效,但请尝试:

gdf.plot(column = "WF_CEREAL", ax = ax, legend=True, categorical=True, cmap='YlOrBr',legend_kwds = {"loc":"lower right"}, figsize =(10,6), legend_labels=["low", "mid", "high", "strong", "severe"])

0
投票

试试这个代码:

gdf.plot(column = "WF_CEREAL", 
         ax = ax, 
         legend=True, 
         categorical=True, 
         cmap='YlOrBr',
         legend_kwds = {'loc':"lower right", 'ticks':[1,2,3,4,5],'format':mticker.FixedFormatter(["low","mid","high","v.high"])})

使用“'format':mticker.FixedFormatter”来设置刻度标签。

© www.soinside.com 2019 - 2024. All rights reserved.