地图上的彩色条

2024-04-29 07:25:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在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工作。


Tags: csvnameimportdataframedfdataplotas
1条回答
网友
1楼 · 发布于 2024-04-29 07:25:54

编辑:下面引用的PR已合并到geopandas master中。现在你可以简单地:

gdf.plot(column='val', cmap='hot', legend=True)

颜色栏将自动添加。

注:

  • legend=True告诉Geopandas添加颜色条。
  • colormap现在称为cmap
  • vminvmax不再是必需的。

有关更多信息,请参见https://geopandas.readthedocs.io/en/latest/mapping.html#creating-a-legend(附带一个如何调整色条大小和位置的示例)。


有一个PR可以将其添加到geoapandas(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的原因是,colorbar不是基于数据本身添加的,因此您必须指示值和颜色之间的链接应该是什么。

相关问题 更多 >