gpt4 book ai didi

r - 无法使用 addLegend(labels) 在 R 中的传单中添加分类图例

转载 作者:行者123 更新时间:2023-12-04 10:56:56 25 4
gpt4 key购买 nike

此问题的所有文件都在 followinggit 中:

我正在尝试在带有分类的传单中绘制分类 map
将字符向量显示为标签的图例:

加载包

首先我加载所需的包

library(rgdal)
library(raster)
library(kableExtra)
library(rasterVis)
library(leaflet)

然后我加载所需的数据集
Codes <- readRDS("Codes.rds")
LandCover <- readRDS("LandCover.rds")

如果我们看一下土地覆盖栅格,它是一个分类栅格,我
ratify 制成从光栅包
LandCover

## class : RasterLayer
## dimensions : 832, 680, 565760 (nrow, ncol, ncell)
## resolution : 30.00002, 29.99993 (x, y)
## extent : 288800.8, 309200.8, 6367272, 6392231 (xmin, xmax, ymin, ymax)
## crs : +proj=utm +zone=19 +south +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
## source : memory
## names : LC_CHILE_2014_b
## values : 150, 932 (min, max)
## attributes :
## ID names IDs
## from: 150 Cultivos 150
## to : 932 Suelos rocosos 932

我想将 name 属性作为图例

使用 levelplot 工作来自 rasterVis 包的函数:
rasterVis::levelplot(LandCover)

如果有效,数据也会在 Codes data.frame 中重述
kable(Codes, caption = "Tabla de atributos del mapa") %>%
kable_styling(bootstrap_options = c("striped", "hover"))

Tabla de atributos del mapa


代码

已选



150

栽培品种


212

Nativo de Hoja Ancha


251

Plantaciones de bosque introducido


330

意大利面


450

马托拉莱斯


510

休谟达莱斯


640

库尔波德阿瓜


800

表层不透水


920

苏埃洛斯·阿里诺索斯


932

罗科索斯苏埃洛斯



两个无效的测试

测试 1
pal <- colorFactor(rainbow(10), values(LandCover),
na.color = "transparent")

leaflet() %>% addTiles() %>% addRasterImage(LandCover, colors = pal, opacity = 0.8) %>% addLegend(pal = pal, values = values(LandCover),title = "Land Cover", labels = Codes$Selected)

enter image description here

测试 2

在第二个中,我认为将标签属性添加到 addLegend函数可以解决问题,但它不起作用
pal <- colorFactor(rainbow(10), values(LandCover),
na.color = "transparent")

leaflet() %>% addTiles() %>% addRasterImage(LandCover, colors = pal, opacity = 0.8) %>% addLegend(pal = pal, values = values(LandCover),title = "Land Cover", labels = Codes$Selected)

enter image description here

最佳答案

您可以通过利用 labFormat 来实现这一点。 addLegend 的论据.
诀窍是使用 transform内函数labFormat将 RAT 的 ID 重新映射到相应的标签。

像这样的事情似乎有效:

library(rgdal)
library(raster)
library(leaflet)

Codes <- readRDS("C:\\Users\\LB_laptop\\Downloads\\Codes.rds")
LandCover <- readRDS("C:\\Users\\LB_laptop\\Downloads\\LandCover.rds")

pal <- colorFactor(rainbow(10), values(LandCover),
na.color = "transparent")

leaflet() %>% addTiles() %>%
addRasterImage(LandCover, colors = pal, opacity = 0.8) %>%
addLegend(pal = pal,
values = values(LandCover),
title = "Land Cover",
labFormat = labelFormat(
transform = function(x) {
levels(LandCover)[[1]]$names[which(levels(LandCover)[[1]]$ID == x)]
}))



创建于 2019-11-30 由 reprex package (v0.3.0)

关于r - 无法使用 addLegend(labels) 在 R 中的传单中添加分类图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59110756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com