在 Geopandas 上添加颜色条

22

我正试图在GeoPandas上创建一个Matplotlib颜色条。

import geopandas as gp
import pandas as pd
import matplotlib.pyplot as plt

#Import csv data
df = df.from_csv('data.csv')

#Convert Pandas DataFrame to GeoPandas DataFrame
g_df = g.GeoDataFrame(df)

#Plot
plt.figure(figsize=(15,15)) 
g_plot = g_df.plot(column='column_name',colormap='hot',alpha=0.08)
plt.colorbar(g_plot)

我遇到了以下错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-55-5f33ecf73ac9> in <module>()
      2 plt.figure(figsize=(15,15))
      3 g_plot = g_df.plot(column = 'column_name', colormap='hot', alpha=0.08)
----> 4 plt.colorbar(g_plot)

...

AttributeError: 'AxesSubplot' object has no attribute 'autoscale_None'

我不确定如何让colorbar起作用。


2
GeoDataFrame返回一个matplotlib Axes对象。plt.colorbar需要一个可映射的对象(一个Axes不是一个可映射的对象)。 - tmdavison
1个回答

58

编辑:下面提到的 PR 已经合并到 geopandas 主分支中。现在您可以直接执行以下操作:

gdf.plot(column='val', cmap='hot', legend=True)
并且颜色条将自动添加。
注意:
- `legend=True` 告诉 Geopandas 添加颜色条。 - `colormap` 现在称为 `cmap`。 - 不再需要使用 `vmin` 和 `vmax`。
有关更多信息,请参见https://geopandas.readthedocs.io/en/latest/mapping.html#creating-a-legend(其中包含如何调整颜色条的大小和位置的示例)。
有一个 PR 将其加入了 GeoPandas (https://github.com/geopandas/geopandas/pull/172),但是现在,您可以使用以下解决方法自行添加它:
## make up some random data
df = pd.DataFrame(np.random.randn(20,3), columns=['x', 'y', 'val'])
df['geometry'] = df.apply(lambda row: shapely.geometry.Point(row.x, row.y), axis=1)
gdf = gpd.GeoDataFrame(df)

## the plotting

vmin, vmax = -1, 1

ax = gdf.plot(column='val', colormap='hot', vmin=vmin, vmax=vmax)

# add colorbar
fig = ax.get_figure()
cax = fig.add_axes([0.9, 0.1, 0.03, 0.8])
sm = plt.cm.ScalarMappable(cmap='hot', norm=plt.Normalize(vmin=vmin, vmax=vmax))
# fake up the array of the scalar mappable. Urgh...
sm._A = []
fig.colorbar(sm, cax=cax)

这个解决方法来自于Matplotlib - add colorbar to a sequence of line plots。你需要自己提供vminvmax的原因是因为颜色栏不是基于数据本身添加的,所以你需要指定值和颜色之间的关系。


它确实会自动添加,但不一定是以良好的方式。请问您能否添加一个链接,以了解如何调整图例的大小、比例、字体和其他格式? - Michael H
文档中有关于如何调整色条的大小和位置的信息:https://geopandas.readthedocs.io/en/latest/mapping.html#creating-a-legend - joris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接