如何用自定义图例绘制地理数据?

How to plot geographic data with customized legend?

有了带值的地理点,我想用颜色图对值进行编码,并自定义图例位置和颜色图范围。

使用 geopandas,我编写了以下函数:

def plot_continuous(df, column_values, title):
    fig = plt.figure()
    ax = fig.add_axes([0, 0, 1, 1])
    ax.axis('off')
    df.plot(ax=ax, column=column_values, cmap='OrRd', legend=True);
    ax.title.set_text(title)

颜色条默认是垂直的,但我想把它变成水平的。

为了有水平颜色条,我写了下面的函数:

def plot_continuous(df, column_values, title, legend_title=None):
    fig = plt.figure()
    ax = fig.add_axes([0, 0, 1, 1])
    x = np.array(df.geometry.apply(lambda x: x.x))
    y = np.array(df.geometry.apply(lambda x: x.y))
    vals = np.array(df[column_values])
    sc = ax.scatter(x, y, c=vals, cmap='OrRd')
    cbar = plt.colorbar(sc, orientation="horizontal")
    if legend_title is not None:
        cbar.ax.set_xlabel(legend_title)
    ax.title.set_text(title)

然而,后一种情况下的图像宽度和高度不成比例,因此输出看起来失真。

有谁知道如何自定义地理图并保持宽高比不失真?

如果您使用 geopandas 自定义 plot()

,这会变得简单得多

记录在案:https://geopandas.org/en/stable/docs/user_guide/mapping.html

下面我展示了 MWE 使用你的函数然后使用 geopandas。稍后已正确缩放数据。

你的代码的 MWE

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

def plot_continuous(df, column_values, title, legend_title=None):
    fig = plt.figure()
    ax = fig.add_axes([0, 0, 1, 1])
    x = np.array(df.geometry.apply(lambda x: x.x))
    y = np.array(df.geometry.apply(lambda x: x.y))
    vals = np.array(df[column_values])
    sc = ax.scatter(x, y, c=vals, cmap='OrRd')
    cbar = plt.colorbar(sc, orientation="horizontal")
    if legend_title is not None:
        cbar.ax.set_xlabel(legend_title)
    ax.title.set_text(title)
    
cities = gpd.read_file(gpd.datasets.get_path("naturalearth_cities"))
cities["color"] = np.random.randint(1,10, len(cities))

plot_continuous(cities, "color", "my title", "Color")

使用 geopandas

ax = cities.plot(
    column="color",
    cmap="OrRd",
    legend=True,
    legend_kwds={"label": "Color", "orientation": "horizontal"},
)

ax.set_title("my title")