[英]Geopandas generate empty plot
我正在學習教程。 基本上,我想要 plot 地面觀測數據點(shapefile)中 scope 光柵格式 40 波段圖像的圖像值。 但是當我嘗試 plot 時,它給了我一個空白的子圖。
#read points from shapefile
train_pts = gpd.read_file (training_points)
train_pts = train_pts[['class', 'classes' ,'CID', 'POINT_X','POINT_Y']] #attribute fields os shapefile
train_pts.index = range(len(train_pts))
coords = [(x,y) for x, y in zip(train_pts.POINT_X, train_pts.POINT_Y)] #create list of point coordinates
#sample each band of raster dataset at each point in the coordinate list
train_pts ['Raster Value'] = [x for x in dataset.sample(coords)] #all band values saved as a list in the Raster Value column
#Unpack the raster value column to separate column for each band
train_pts[band_names] = pd.DataFrame(train_pts['Raster Value'].tolist(), index = train_pts.index)
train_pts = train_pts.drop(['Raster Value'], axis=1) #drop raster value column
#change the values for last three classes
train_pts['CID'] = train_pts['CID'].replace([7,8,15],[5,6,7])
train_pts.to_csv('train_pts2.csv') #save as csv
train_pts.head (30) #see columns
這段代碼的輸出是這樣的: 然后我運行此代碼以使用此代碼獲取子圖:
prof = train_pts.groupby (['classes']).mean ()
fig = plt.figure(figsize = (17,20))
band_n = [ 'B2', 'B3', 'B4', 'B8' ,'NDVI' ,'VH', 'VV']
n = 1
for ba in band_n:
ax = fig.add_subplot(4,2,n)
ax.title.set_text(ba)
band_val = prof[prof.columns[prof.columns.to_series().str.contains(ba)]]
for index, row in band_val.iterrows():
color = cmap (index)
ax.plot (row,color=color)
ax.autoscale(enable=True, axis="both", tight=None)
ax.set_xticklabels([str (x) for x in range(1, len(row)+1)])
ax.legend(loc='best', fontsize='small', ncol=2, labels=class_names)
n=n+1
我還仔細檢查了光柵和點數據的投影,它是一樣的。 我還能做什么?
matplotlib.pyplot.plot
創建線圖。 當你像你一樣循環遍歷行和列時,你最終只會將一個點傳遞給每個 plot 命令,所以你正在繪制一堆長度為 0 的線。
我想你想要matplotlib.pyplot.scatter
,並將x
、 y
和c
的完整列作為 arguments 傳遞。來自plt.scatter
文檔:
matplotlib.pyplot.scatter
(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, *, edgecolors=None, plotnonfinite=False, data=None, **kwargs)
具有不同標記大小和/或顏色的 y 與 x 的散點圖 plot。參數
x, y:浮點數或類數組,形狀 (n, )
數據位置。...
c:類似數組或 colors 或顏色的列表,可選
標記 colors。
因此,對於 plot 柵格中的所有點,每列只需 plot 一次:
for i, ba in enumerate(band_n):
ax = fig.add_subplot(4, 2, i +1)
band_val = prof[prof.columns[prof.columns.str.contains(ba)]]
# check to make sure you're matching exactly one column
assert band_val.shape[1] == 1, (
f"unexpected columns: {band_val.columns}"
)
ax.scatter(
x=prof['POINT_X'],
y=prof['POINT_Y'],
c=band_val.iloc[:, 0],
)
根據您的數據大小和點密度,渲染可能需要很長時間,並且點本身可能會重疊。 相反,您可能想要查看matplotlib.pyplot.pcolormesh
,它可以在常規網格上顯示 plot 數據。
也就是說,如果您的數據位於常規網格上,您可能需要查看xarray ,它設置得很好,可以處理網格化數據。 您需要確保您的 x 和 y 值是規則的完整網格的索引,例如,對於 x 的每個組合,y 的每個值都完全重復。 但如果是這種情況,您可以使用 df.to_xarray 將 dataframe 轉換為df.to_xarray
數據集: ds = prof.set_index(['POINT_X', 'POINT_Y']).to_xarray()
然后 plot 使用ds[band_name].plot()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.