Geopandas上的颜色栏 [英] Colorbar on Geopandas
问题描述
我正在尝试在GeoPandas上创建Matplotlib颜色条.
I am trying to create a Matplotlib colorbar on GeoPandas.
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'
我不确定如何使颜色栏正常工作.
I am not sure how to get colorbar to work.
推荐答案
编辑:以下引用的PR已合并到geopandas母版中.现在您可以轻松地做到:
The PR referenced below has been merged into the geopandas master. Now you can simply do:
gdf.plot(column='val', cmap='hot', legend=True)
,然后会自动添加颜色栏.
and the colorbar will be added automatically.
注意:
-
legend=True
告诉Geopandas添加颜色条. -
colormap
现在称为cmap
. -
vmin
和vmax
不再需要.
legend=True
tells Geopandas to add the colorbar.colormap
is now calledcmap
.vmin
andvmax
are not required anymore.
请参见 https://geopandas.readthedocs.io/en /latest/mapping.html#creating-a-legend (包括如何调整颜色栏的大小和位置的示例).
See https://geopandas.readthedocs.io/en/latest/mapping.html#creating-a-legend for more (with an example how to adapt the size and placement of the colorbar).
有一个PR可以将其添加到geoapandas中( https://github.com/geopandas/geopandas/pull/172 ),但目前,您可以使用以下解决方法自行添加:
There is a PR to add this to geoapandas (https://github.com/geopandas/geopandas/pull/172), but for now, you can add it yourself with this workaround:
## 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-添加颜色条以绘制一系列的线图.而且,您必须自己提供vmin
和vmax
的原因是因为未根据数据本身添加颜色条,因此必须指示值和颜色之间的联系.
The workaround comes from Matplotlib - add colorbar to a sequence of line plots. And the reason that you have to supply vmin
and vmax
yourself is because the colorbar is not added based on the data itself, therefore you have to instruct what the link between values and color should be.
这篇关于Geopandas上的颜色栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!