我正在處理 R 中的光柵影像,目的是將處理后的影像匯出為與輸入資料具有相同尺寸的 tiff。我需要將美學程序應用于 ggplot 中的資料(我不會在這篇文章中討論),這就是為什么我將其處理為 ggplot 而不是作為柵格。在 ggplot 中創建繪圖后,我想以與輸入柵格相同的解析度匯出為 tiff,沒有線條或邊距。
下面是一個示例資料集。您可以在下面的示例中看到輸入柵格為 87 x 61 像素。我想匯出尺寸完全相同的 tiff。下面是我的嘗試。當我作為 tiff 匯出時,ggplot 包括我不想要的圖周圍的邊距(我嚴格只想要與柵格中的輸入單元格一致的輸入單元格。
volcano_raster <- raster(volcano, xy = TRUE)
volcano_raster
# You can see below that the input raster is 87, 61 cells.
class : RasterLayer
dimensions : 87, 61, 5307 (nrow, ncol, ncell)
resolution : 0.01639344, 0.01149425 (x, y)
extent : 0, 1, 0, 1 (xmin, xmax, ymin, ymax)
crs : NA
source : memory
names : layer
values : 94, 195 (min, max)
volcano_raster_df <- volcano_raster %>% as.data.frame(., xy = TRUE) %>% rename(layer = 3)
volcano_gg <- ggplot()
geom_raster(data = volcano_raster_df,
aes(x = x, y = y,
fill = layer))
scale_fill_gradient(low = "black", high = 'red')
ggmap::theme_nothing()
theme(legend.position="none")
theme(plot.margin = grid::unit(c(0,0,0,0), "mm"),
axis.ticks.length = unit(0, "pt"),
axis.text=element_blank(),
axis.title=element_blank())
labs(x = NULL, y = NULL)
# Here I export the plot as a tiff using the same dimensions as those in the raster.
ggsave(plot=volcano_gg, "vol_gg_df.tiff", device = "tiff", units = 'px', width = 61, height = 86)

uj5u.com熱心網友回復:
洗掉圖例(在scale...級別),使用theme_void()x 和 y 軸擴展并將其設定為零對我來說是訣竅。
## using "volcano_raster_df" from your example:
volcano_raster_df %>%
ggplot()
geom_raster(aes(x, y, fill = layer))
scale_fill_gradient(low = "black",
high = 'red',
guide = 'none' ## omit legend
)
scale_x_continuous(expand = c(0, 0))
scale_y_continuous(expand = c(0, 0))
theme_void()
ggsave("vol_gg_df.tiff", device = "tiff",
units = 'px', width = 61, height = 86)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/468213.html
