【问题标题】:Colorbar on GeopandasGeopandas 上的颜色条
【发布时间】:2016-06-30 17:41:53
【问题描述】:

我正在尝试在 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'

我不确定如何让颜色条工作。

【问题讨论】:

  • GeoDataFrame 返回一个 matplotlib Axes 对象。 plt.colorbar 需要可映射对象(Axes 不是可映射对象)。

标签: python pandas matplotlib geopandas


【解决方案1】:

编辑: 下面引用的 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 的原因是因为颜色条不是根据数据本身添加的,因此您必须指示值和颜色之间的链接应该是什么。

【讨论】:

  • 它确实会自动添加,但不一定是好的方式。您能否添加一个链接到信息请如何调整大小、缩放、设置字体和以其他方式格式化图例?
  • 文档中有一些关于如何调整颜色条的大小和位置的信息:geopandas.readthedocs.io/en/latest/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-17
  • 1970-01-01
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多