繁体   English   中英

geopandas plot 中用于颜色和标记大小的图例

[英]Legend in geopandas plot for color as well as for markersize

我正在创建一个 geopandas plot ,其中 colors 取决于列值,而标记大小取决于另一个列值。 当我输入 legend=True 时,plot 仅在图例中显示 colors 而不是标记大小的值。 任何人都知道如何添加它。

看我的代码:

fig, ax = plt.subplots(1, 1, figsize= (20, 20))

regions_un = np.unique(region)
color = {}

for i in range(len(regions_un)):
    color[regions_un[i]] = '#%06X' % randint(i, 0xFFF)
    
df_deltas_cities['color'] = df_deltas_cities['region'].map(color)

df_deltas_cities.loc[df_deltas_cities["R"] < 0, "R"] = 0
df_deltas_cities['markersize'] = df_deltas_cities['R']**2

world.plot(ax= ax, color= 'lightgrey');
df_deltas_cities.plot(column= 'region', ax=ax, markersize= 'markersize', c = df_deltas_cities['color'], legend= True);

结果图: 在此处输入图像描述

我想添加到图例中的是这样的: 在此处输入图像描述

问候,

但丁

  • 通过重用内置的geopandas示例几何使代码可运行
  • 您可以添加第二个图例,其中标记大小缩放为数据框中的数值
import matplotlib.pyplot as plt
import geopandas as gpd
import numpy as np
import matplotlib.lines as mlines
import pandas as pd

world = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))
df_deltas_cities = gpd.read_file(gpd.datasets.get_path("naturalearth_cities"))
df_deltas_cities["region"] = np.random.choice(
    ["Cities", "Deltas", "Cities+Deltas"], len(df_deltas_cities)
)

df_deltas_cities["markersize"] = np.random.uniform(5, 400, len(df_deltas_cities))
df_deltas_cities["color"] = df_deltas_cities["region"].map(
    {a: b for a, b in zip(df_deltas_cities["region"].unique(), "rgb")}
)
fig, ax = plt.subplots(1, 1, figsize=(8, 8))

ax = world.plot(ax=ax, color="lightgrey")
ax = df_deltas_cities.plot(
    column="region",
    ax=ax,
    markersize="markersize",
    c=df_deltas_cities["color"],
    legend=True,
)

# need to add existing legend back
leg1 = ax.get_legend()

# some bins to indicate size in legend
_, bins = pd.cut(df_deltas_cities["markersize"], bins=3, precision=0, retbins=True)
# create second legend
ax.add_artist(
    ax.legend(
        handles=[
            mlines.Line2D(
                [],
                [],
                color="black",
                lw=0,
                marker="o",
                markersize=2**i,
                label=str(int(b)),
            )
            for i, b in enumerate(bins)
        ],
        loc=4,
    )
)
# restore original legend
ax.add_artist(leg1)

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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