簡體   English   中英

AttributeError:在郵政編碼 shp 文件中繪制事件的 Geopandas 中的未知屬性列

[英]AttributeError: Unknown property column in Geopandas plotting of events in zipcode shp file

我正在嘗試創建一個 Choropleth 地圖,顯示整個北卡羅來納州一個縣的火災事件。 我在 Dataframe 中有數據,昨晚我能夠導出地圖。 唯一的問題是導出的數據不准確——所以我的代碼有問題。 我想我設法通過將 shapefile 和數據數據幀合並在一起來解決這個問題,但是現在,當我運行創建地圖的部分時,我收到AttributeError: Unknown property column Full 消息:

AttributeError                            Traceback (most recent call last)
<ipython-input-74-61a60b41abbe> in <module>()
    13 # create map
    14 
---> 15 merged_df.plot(column=variable, cmap='Reds', linewidth=0.8, ax=ax, edgecolor='0.8');
    16 
    17 ax.axis('off')

~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in __call__(self, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds)
  2939                           fontsize=fontsize, colormap=colormap, table=table,
  2940                           yerr=yerr, xerr=xerr, secondary_y=secondary_y,
-> 2941                           sort_columns=sort_columns, **kwds)
  2942     __call__.__doc__ = plot_frame.__doc__
  2943 

~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in plot_frame(data, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds)
  1975                  yerr=yerr, xerr=xerr,
  1976                  secondary_y=secondary_y, sort_columns=sort_columns,
-> 1977                  **kwds)
  1978 
  1979 

~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in _plot(data, x, y, subplots, ax, kind, **kwds)
  1802         plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds)
  1803 
-> 1804     plot_obj.generate()
  1805     plot_obj.draw()
  1806     return plot_obj.result

~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in generate(self)
   258         self._compute_plot_data()
   259         self._setup_subplots()
--> 260         self._make_plot()
   261         self._add_table()
   262         self._make_legend()

~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in _make_plot(self)
   983                              stacking_id=stacking_id,
   984                              is_errorbar=is_errorbar,
--> 985                              **kwds)
   986             self._add_legend_handle(newlines[0], label, index=i)
   987 

~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in _plot(cls, ax, x, y, style, column_num, stacking_id, **kwds)
   999             cls._initialize_stacker(ax, stacking_id, len(y))
  1000         y_values = cls._get_stacked_values(ax, stacking_id, y, kwds['label'])
-> 1001         lines = MPLPlot._plot(ax, x, y_values, style=style, **kwds)
  1002         cls._update_stacker(ax, stacking_id, y)
  1003         return lines

~\Anaconda3\lib\site-packages\pandas\plotting\_core.py in _plot(cls, ax, x, y, style, is_errorbar, **kwds)
   613             else:
   614                 args = (x, y)
--> 615             return ax.plot(*args, **kwds)
   616 
   617     def _get_index_name(self):

~\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
  1808                         "the Matplotlib list!)" % (label_namer, func.__name__),
  1809                         RuntimeWarning, stacklevel=2)
-> 1810             return func(ax, *args, **kwargs)
  1811 
  1812         inner.__doc__ = _add_data_doc(inner.__doc__,

~\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in plot(self, scalex, scaley, *args, **kwargs)
  1609         kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)
  1610 
-> 1611         for line in self._get_lines(*args, **kwargs):
  1612             self.add_line(line)
  1613             lines.append(line)

~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _grab_next_args(self, *args, **kwargs)
   391                 this += args[0],
   392                 args = args[1:]
--> 393             yield from self._plot_args(this, kwargs)
   394 
   395 

~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup, kwargs)
   381                                   "with non-matching shapes is deprecated.")
   382         for j in range(max(ncx, ncy)):
--> 383             seg = func(x[:, j % ncx], y[:, j % ncy], kw, kwargs)
   384             ret.append(seg)
   385         return ret

~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _makeline(self, x, y, kw, kwargs)
   286         default_dict = self._getdefaults(None, kw)
   287         self._setdefaults(default_dict, kw)
--> 288         seg = mlines.Line2D(x, y, **kw)
   289         return seg
   290 

~\Anaconda3\lib\site-packages\matplotlib\lines.py in __init__(self, xdata, ydata, linewidth, linestyle, color, marker, markersize, markeredgewidth, markeredgecolor, markerfacecolor, markerfacecoloralt, fillstyle, antialiased, dash_capstyle, solid_capstyle, dash_joinstyle, solid_joinstyle, pickradius, drawstyle, markevery, **kwargs)
   408         # update kwargs before updating data to give the caller a
   409         # chance to init axes (and hence unit support)
--> 410         self.update(kwargs)
   411         self.pickradius = pickradius
   412         self.ind_offset = 0

~\Anaconda3\lib\site-packages\matplotlib\artist.py in update(self, props)
   914 
   915         with cbook._setattr_cm(self, eventson=False):
--> 916             ret = [_update_property(self, k, v) for k, v in props.items()]
   917 
   918         if len(ret):

~\Anaconda3\lib\site-packages\matplotlib\artist.py in <listcomp>(.0)
   914 
   915         with cbook._setattr_cm(self, eventson=False):
--> 916             ret = [_update_property(self, k, v) for k, v in props.items()]
   917 
   918         if len(ret):

~\Anaconda3\lib\site-packages\matplotlib\artist.py in _update_property(self, k, v)
   910                 func = getattr(self, 'set_' + k, None)
   911                 if not callable(func):
--> 912                     raise AttributeError('Unknown property %s' % k)
   913                 return func(v)
   914 

AttributeError: Unknown property column

我不知道如何解決這個問題。 我用谷歌搜索並嘗試將 dtype 從 float 更改為 int,嘗試了不同的列,但沒有任何變化。 我不明白,因為它昨晚起作用了,但是當我今天嘗試在進行更改之前運行它時卻不起作用。 預先感謝您的任何幫助。 下面是我的大部分代碼,其中包含數據框和映射,其他一切都只是從 csvs 獲取數據:

import pandas as pd
import numpy as np
#import googlemaps
import gmaps
import gmaps.datasets
import geopandas as gpd
#import matplotlib as plt
import matplotlib.pyplot as plt
import os
import plotly.plotly as py
import plotly.tools as tls

這是合並后的數據框的樣子: 在此處輸入圖片說明

OBJECTID_x                     int64
ZIPNUM                       float64
address                       object
address2                      object
apt_room                      object
arrive_date_time              object
cleared_date_time             object
dispatch_date_time            object
exposure                       int64
incident_number               object
incident_type                  int64
incident_type_description     object
platoon                       object
station                      float64
Longitude                     object
Latitude                      object
Year                           int64
Date                          object
Arr Time                      object
Seconds                      float64
Incident                      object
OBJECTID_y                     int64
ZIPNAME                       object
ZIPCODE                       object
NAME                          object
SHAPEAREA                    float64
SHAPELEN                     float64
LAST_EDITE                    object
geometry                      object
dtype: object
# set a variable that will call column to visualise on the map

variable = 'ZIPNUM'

# set the range for the choropleth

vmin, vmax = 50, 2000

# create figure and axes for Matplotlib

fig, ax = plt.subplots(1, figsize=(15, 15))

# create map

merged_df.plot(column=variable, cmap='Reds', linewidth=0.8, ax=ax, edgecolor='0.8');

ax.axis('off')

ax.set_title('Fire Incident Rate in Wake County', fontdict={'fontsize': '25', 'fontweight' : '3'})

# Create colorbar as a legend

sm = plt.cm.ScalarMappable(cmap='Reds', norm=plt.Normalize(vmin=vmin, vmax=vmax))

# empty array for the data range

sm._A = []

# add the colorbar to the figure

cbar = fig.colorbar(sm)

ax.annotate('2008-2018',
            xy=(0.001, .225), xycoords='figure fraction',
            horizontalalignment='left', verticalalignment='top',
            fontsize=35)

fig.savefig("Fire Incident Rate in Wake County 2008-2018.png", dpi=300)

問題是您試圖使用column作為關鍵字參數。 由於您想繪制存儲在名為variable的變量中的 DataFrame 的'ZIPNUM'列,您可以將其作為位置參數傳遞給plot() 如果你想繪制兩個變量之間的關系,你可以使用關鍵字參數merged_df.plot(x=variable1, y=variable2)

對於你的情況,你可以使用

variable = 'ZIPNUM'
merged_df.plot(variable, cmap='Reds', linewidth=0.8, ax=ax, edgecolor='0.8');

編輯(基於評論)

當您使用marker進行繪圖時才應使用marker markeredgecolor edgecolor不是正確的關鍵字。 此外,您正在分配一個數字(字符串)作為顏色,這又是不正確的。 下面是一個簡單的例子。

df = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]], columns=["A", "B"])
column='A'
df.plot(column, linewidth=0.8, color='r', marker ='o', markeredgewidth=2,
        markeredgecolor='blue')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM