3

I'm using pandas, geopandas, and cartopy to make spatial plots for data points.

Everything works fine, except for when I try to add color bar.

Below is my code and the error. Any help is appreciated.

fig = plt.figure()

ax = plt.axes(projection=ccrs.PlateCarree())

reader = shpreader.Reader('countyl010g.shp')

counties = list(reader.geometries())

COUNTIES = cfeature.ShapelyFeature(counties, ccrs.PlateCarree())

ax.add_feature(COUNTIES, facecolor='none', edgecolor='gray')

ax.coastlines()

ax.add_feature(cartopy.feature.STATES)


dp=pd.read_csv('Arash.csv',index_col=False)

def remove_minutes(state):
  state=datetime.datetime.strptime(state, '%Y-%m-%d %H:%M:%S')
  state= state.replace(minute=0)
  return state

dp['TIMESTAMP']=dp['TIMESTAMP'].apply(remove_minutes)

dp.set_index(['TIMESTAMP'], inplace=True)

dp= dp[dp.index.day == 28]

dp['coordinates'] = dp[['Longitude', 'Latitude']].values.tolist()

dp['coordinates'] = dp['coordinates'].apply(Point)

dp = gpd.GeoDataFrame(dp, geometry='coordinates')

ac=dp.plot(ax=ax,column='CO_CMAQ',markersize=0.05,cmap='turbo')

ax.set_xlim(-119,-117)

ax.set_ylim(33.5,34.5)

fig.colorbar(ac,ax=ax)

And here is the error:

File "C:\Python-practice\GHG\spatial_plot_mobile.py", line 102, in fig.colorbar(ac,ax=ax)

File "C:\Users\akash\anaconda3\lib\site-packages\matplotlib\figure.py", line 2343, in colorbar cb = cbar.colorbar_factory(cax, mappable, **cb_kw)

File "C:\Users\akash\anaconda3\lib\site-packages\matplotlib\colorbar.py", line 1734, in colorbar_factory cb = Colorbar(cax, mappable, **kwargs)

File "C:\Users\akash\anaconda3\lib\site-packages\matplotlib\colorbar.py", line 1202, in init

if mappable.get_array() is not None: AttributeError: 'GeoAxesSubplot' object has no attribute 'get_array'

Thank you again,

ZINE Mahmoud
  • 1,272
  • 1
  • 17
  • 32

1 Answers1

0

Old question, but I landed on it because I had an analogous error, so in case it helps anyone else in future:

The problem is that ac here is a GeoAxesSubplot object within a Matplotlib figure. When Matplotlib is given fig.colorbar(ac,ax=ax), it doesn't know what to do with ac.

As per the Geopandas documentation, the information about the colorbar needs to go into the Geopandas .plot() itself, so that the relevant line above would look something like:

ac=dp.plot(ax=ax,column='CO_CMAQ',markersize=0.05,cmap='turbo', 
           legend=True, legend_kwds={'label':"",'orientation':""})

with the legend_kwds filled in as desired, e.g. orientation="horizontal".

More advice on modifying Geopandas colorbars here.