matplotlib 颜色Map表的自定义记号标签

gj3fmq9x  于 2023-05-07  发布在  其他
关注(0)|答案(1)|浏览(145)

bounty还有5天到期。回答此问题可获得+50声望奖励。Stücke正在寻找典型答案

我有一个情节,包括一个3种颜色的色图。

import geopandas
import matplotlib.cm as cm
import matplotlib.pyplot as plt

world = geopandas.read_file(
    geopandas.datasets.get_path('naturalearth_lowres')
    )

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

cmap = cm.get_cmap('PiYG', 3)

world.plot(
    column='pop_est',
    ax=ax,
    legend=True,
    cmap=cmap
    )

如何将自定义刻度线添加到色彩Map表/图例?legend_kwds={'ticks': ['Low','Medium','High']}产生TypeError: '<=' not supported between instances of 'numpy.ndarray' and 'numpy.ndarray'cmap.ax.set_xticklabels(['Low', 'Medium', 'High'])产生AttributeError: 'LinearSegmentedColormap' object has no attribute 'ax'

dy2hfwbg

dy2hfwbg1#

为了实现这一点,您需要自己设置一个单独的颜色栏来实现您所需要的。在你的代码中,保持legend为false,然后根据需要创建一个新的colorbar...更新以下代码。

import geopandas
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.colors as colors ## Added newly

world = geopandas.read_file(
    geopandas.datasets.get_path('naturalearth_lowres')
    )

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

cmap = cm.get_cmap('PiYG', 3)

world.plot(
    column='pop_est',
    ax=ax,
    legend=False,  ## Note - changed to False
    cmap=cmap,
    )

## Create new Colorbar with info you want...
norm=colors.Normalize(vmin=world.pop_est.min(), vmax=world.pop_est.max())
cbar=plt.cm.ScalarMappable(norm=norm, cmap=cm.get_cmap('PiYG', 3))
axCbar=fig.colorbar(cbar, ax=ax)
axCbar.set_ticks([200000000,700000000,1200000000])
axCbar.set_ticklabels(["Low","Medium","High"])

相关问题