更改Geopandas Choropleth地图图例的输入顺序 [英] Changing the order of entries for a geopandas choropleth map legend

查看:174
本文介绍了更改Geopandas Choropleth地图图例的输入顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在城市地图上绘制某种分类值.我用来绘制的代码行如下:

I am plotting a certain categorical value over the map of a city. The line of code I use to plot is the following:

fig = plt.figure(figsize=(12, 12))
ax = plt.gca()
urban_data.plot(column="category", cmap="viridis", ax=ax, categorical=True, /
                k=4, legend=True, linewidth=0.5, /
                legend_kwds={'fontsize':'19', 'loc':'lower left'}) 

其中城市数据是地理大熊猫的数据框,我正在使用matplotlib作为绘图库.自变量legend_kwds允许我控制图例上的次要内容,例如位置或字体大小,但是我不能决定主要内容,例如图例框中条目的顺序.实际上,我的类别是排名,例如1-2-3-4,但是我总是以不同的顺序显示它们.

where urban data is a geopandas dataframe, and I am using matplotlib as plotting library. The argument legend_kwds allows me to control minor things on the legend, like the position or the font size, but I cannot decide major things like, for example, the order of the entries in the legend box. In fact my categories are ranked, let's say 1-2-3-4, but I always get them displayed in a different order.

是否可以对图例进行更多控制?例如,通过在函数中调用它 outside ?而且,如果是这样,我该如何将图例中的颜色与地图中的颜色进行匹配,这些颜色是翠绿颜色图的离散值(我不清楚)?

Is it possible to have more control over the legend? For example by calling it outside the gdf.plot() function? And, if so, how do I match the colors in the legend with those in the map, which are discrete values (that I don't know exactly) of a viridis colormap?

这是一个可验证的示例.不幸的是,shapefile需要其他文件才能工作,这里需要一个geometry(区域,而不是一个点)列,所以我必须请您下载

here is a verifiable example. Unfortunately shapefiles need other files to work, and here a geometry (an area, not a point) column is needed, so I have to ask you to download this shpfile of the US. Everything you need is within this folder. Here's the code to reproduce the issue. The plot in output is bad because I did not care about the coordinates system here, but the important thing is the legend.

import geopandas as gpd
import numpy as np
import matplotlib.pyplot as plt 

gdf=gpd.read_file('.../USA_adm1.shp')
clusters=np.random.randint(0,4, size=52)
gdf['cluster']=clusters
clusdict={1: 'lower-middle', 2: 'upper-middle', 3: 'upper', 0: 'lower'}
gdf['cluster']=gdf['cluster'].map(clusdict)

fig = plt.figure(figsize=(12, 12))
ax = plt.gca()
gdf.plot(column='cluster',cmap='viridis', categorical=True, legend=True, ax=ax)

推荐答案

坏消息是,geopandas生成的图例中的类别已排序,并且经过了硬编码(

The bad news is that categories in legends produced by geopandas are sorted and this is hardcoded (see source-code here).

因此,一种解决方案是拥有类别列,以便如果对其进行排序,它将与所需的顺序相对应.为此,使用整数似乎很好.一旦按照正确的顺序生成了图例,就可以替换图例中的名称.

One solution is hence to have the categorical column such that if it is sorted, it would correspond to the desired order. Using integers seems fine for that. Then one can replace the names in the legend, once it is produced in the correct order.

import geopandas as gpd
import numpy as np
import matplotlib.pyplot as plt 

gdf=gpd.read_file('data/USA_adm/USA_adm1.shp')
clusters=np.random.randint(0,4, size=52)
gdf['cluster']=clusters
clusdict={1: 'lower-middle', 2: 'upper-middle', 3: 'upper', 0: 'lower'}

fig = plt.figure(figsize=(12, 12))
ax = plt.gca()
gdf.plot(column='cluster',cmap='viridis', categorical=True, legend=True, ax=ax)

def replace_legend_items(legend, mapping):
    for txt in legend.texts:
        for k,v in mapping.items():
            if txt.get_text() == str(k):
                txt.set_text(v)

replace_legend_items(ax.get_legend(), clusdict)

plt.show()

这篇关于更改Geopandas Choropleth地图图例的输入顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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