Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 向绘图添加图例时为什么会出现错误?_R_Plot_Classification_Raster_Shapefile - Fatal编程技术网

R 向绘图添加图例时为什么会出现错误?

R 向绘图添加图例时为什么会出现错误?,r,plot,classification,raster,shapefile,R,Plot,Classification,Raster,Shapefile,我正在尝试使用下面的代码将图例添加到我的分类图中 library(raster) library(RStoolbox) landsat5 <- stack('lt05.tif') shp<-shapefile("to5/to.shp") SC_rf <- superClass(landsat5, shp, responseCol = "MC_ID", nSamples = 1000, polygonBasedCV = TRUE,

我正在尝试使用下面的代码将图例添加到我的分类图中

library(raster)
library(RStoolbox)
landsat5 <- stack('lt05.tif')
shp<-shapefile("to5/to.shp")
SC_rf <- superClass(landsat5, shp, responseCol = "MC_ID",
                    nSamples = 1000, polygonBasedCV = TRUE,
                    model = "rf", tuneLength = 5, kfold = 5,
                    mode = "classification", predType = "raw", overwrite = TRUE)
## Plots
colors <- c("yellow", "green", "deeppink", "orange", "red")
plot(SC_rf$map, col = colors, legend = TRUE, axes = FALSE, box = FALSE)
legend(1, 1, legend = levels(shp$MC_info), fill = colors , title = "Classes")
库(光栅)
图书馆(RStoolbox)

landsat5
MC_info
似乎是一个向量,而不是一个因子,因此不需要使用
levels()
。要访问shapefile对象中的数据,请尝试通过
光栅
包中的
as.data.frame()
函数将其转换为:

legend(1, 1, legend = raster::as.data.frame(shp)$MC_info, fill = colors , title = "Classes")
或者您可以为此定义一个变量:

shp_df <- raster::as.data.frame(shp)
legend(1, 1, legend = shp_df$MC_info, fill = colors , title = "Classes")

shp\u df
shp$data$MC\u info
?没有帮助,仍然给出相同的错误是的,在这两种情况下给出的“图例”距离图像的长度均为0,
shp
没有名为
MC\u info
的单元格
MC_info
位于
shp$data
中。
shp$MC\u info
是否返回任何内容?它的类别是什么?
shp$MC_info
不再显示错误,但仍然不显示图例。shp有空间多边形数据框类不再显示错误,但仍然不显示MC_信息中的名称,而只显示MC_ID中的数字1-5…@Aisyram我不太熟悉空间多边形,但您可以尝试在
plot()
中取消默认图例,如
plot(…,legend=FALSE)
以使图例()生效?看下面。让我知道这是否有效…@Aiyram Hi,我尝试使用shapefile对象,在我看来,要访问其数据,您需要使用
光栅
包中的
as.data.frame()
函数。我已经更新了答案,请试试这个,让我知道。还是一样。。。但我找到了另一个解决方案:
par(xpd=FALSE,mar=c(1,1,1,1))plot(scu knn$map,col=colors,breaks=brk,main=“K-近邻分类”,legend=FALSE,axes=FALSE,box=FALSE)par(xpd=TRUE)legend(“右”,legend=c(“Woda”,“Zabudowa miejska”,“Roślinnośćniska”,“Grunty”,“Drzewa”),fill=rev(colors),inset=-0.5,cex=0.8,title=“Klasy:”,title.adj=0.1)
虽不完美,但相当有效。