从.tif文件中提取颜色在R中的处理

3
我想修改我的.tif文件中的颜色。我已经将文件上传在这里
读取它并快速查看它似乎所有信息都在那里。
library(dplyr);library(ggplot2)
library(raster)
pic <- raster::brick(x="SUB_IMG_8020 (1)_A_36x36.tif")
pic
class      : RasterBrick 
dimensions : 619, 1060, 656140, 3  (nrow, ncol, ncell, nlayers)
resolution : 1, 1  (x, y)
extent     : 0, 1060, 0, 619  (xmin, xmax, ymin, ymax)
crs        : NA 
source     : SUB_IMG_8020 (1)_A_36x36.tif 
names      : SUB_IMG_8020_.1._A_36x36.1, SUB_IMG_8020_.1._A_36x36.2,     SUB_IMG_8020_.1._A_36x36.3 
min values :                          0,                          0,                          0 
max values :                        255,                        255,                        255 

plotRGB(pic)

example plot using plot plotRGB

到目前为止一切都很好。现在我想手动更改颜色,因此我将对象转换为data.frame以便使用ggplot2。但是,在某个地方,我正在丢失信息。有人知道如何解决这个问题吗?

test_spdf <- as(pic, "SpatialPixelsDataFrame")
#extract colors
test_df <- as.data.frame(test_spdf) %>% 
   mutate(cols = rgb(SUB_IMG_8020_.1._A_36x36.1,   
                SUB_IMG_8020_.1._A_36x36.2, 
                SUB_IMG_8020_.1._A_36x36.3, 
                maxColorValue = 255)) %>%
   dplyr::select(x, y, cols) %>% arrange(x) %>%
   tibble::rowid_to_column("nr")


ggplot(test_df, aes(x=x, y=y)) +  
  geom_raster(aes(fill=cols))+
  theme_void()+
  theme(legend.position="none")+
  coord_fixed()

enter image description here

这按预期工作。但当指定 scale_fill_manual 时,我得到了一个奇怪的图形,表明在提取颜色时出现了错误:
 ggplot(test_df, aes(x=x, y=y)) +  
  geom_raster(aes(fill=cols))+
  scale_fill_manual(values=c(test_df$cols))+
  theme_void()+
  theme(legend.position="none")+
  coord_fixed()

enter image description here

我该如何正确访问似乎存在的颜色(plotRGB输出的结果)?谢谢!

1个回答

1
这是一个很好的使用 scale_fill_identity() 而不是 scale_fill_manual 的地方。否则,填充颜色将被分配在与您预期不同的顺序中。
ggplot(test_df, aes(x=x, y=y)) +  
  geom_raster(aes(fill=cols))+
  theme_void()+
  theme(legend.position="none")+
  scale_fill_identity() +     # SWEET SWEET COLOR ASSIGNMENT MAGIC
  coord_fixed()

你的 scale_fill_manual 方法未能奏效的原因是ggplot首先确定了分配给填充美学的值列表,并按字母顺序创建组。 因此,在这里我们可以看到的JPEG中,十六进制代码“#290000”定义了将接收填充颜色的第一组点,“#320500”定义了第二组点,以此类推。 当使用scale_fill_manual时,ggplot会取用您提供的颜色向量,并依次将其分配给每个组。 如果您按照原始数据框的顺序给出完整的颜色列表,则结果将是颜色混乱,因为它们的顺序(和长度)与scale_fill_manual所期望的不同。 如果您想在这里使用scale_fill_manual,您可以首先获取(按字母顺序排序的)颜色列表,然后将其作为您的填充值列表提供。
library(dplyr)
test_df %>% 
  arrange(cols) %>%        # sort alphabetically
  distinct(cols) %>%       # drop dupes
  pull(cols) -> col_list   # extract column as vector and save to col_list

ggplot(test_df, aes(x=x, y=y)) +  
  geom_raster(aes(fill=cols))+
  theme_void()+
  theme(legend.position="none")+
  scale_fill_manual(values=c(col_list))+
  coord_fixed()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接