简体   繁体   中英

Using ggplot2 to plot TIFF data

I am trying to import raster TIFF in r and plot it using ggplot2. But when I import the file, somehow the X and Y values get lost. I checked the projection system and it is showing WGS which is correct. The extent too is correct. I looked up the image again in ArcMap and I can see the projections there (meaning that its still there).

> extent(file.name)
class      : Extent 
xmin       : 85.94994 
xmax       : 87.45825 
ymin       : 22.31023 
ymax       : 23.48127

> crs(file.name)
CRS arguments:
 +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0 

Despite no X and Y values, I first tried plotting it using nrow and ncol as x and y resp (which didn't make sense to me). I then tried creating a grid but it throws an error. Anyways, it shows a grey map with absolutely nothing in it. The legends are correct.

Code for creating a grid.

start_lat <- 21
start_lng <- 84
griddf <- expand.grid(latcoords = seq(from = start_lat, by = -0.01, l = ncell(file.name)), +
lngcoords = seq(from = start_lng, by = -0.01, l = ncell(file.name))) 

Error: cannot allocate vector of size 24.1 Gb

This is the code I used for plotting.

library(raster)
library(rgdal)
library(ggplot2)

file.name <- raster("path and name of the file.tif")
file_df <- as.data.frame(file.name)

ggplot() +
  geom_raster(data = file_df , aes(x = nrow(file.name), y = nrow(file.name), fill = spei_03)) + #spei_03 is the name of the column whose values I want to plot. 
  scale_fill_viridis_c() +
  coord_quickmap()

I am a newbie in R and can't seem to get my head around it. I searched for answers online but couldn't find one. Please help me in 1) How to bring X and Y data into R, and 2) How to create a ggplot that works.

enter image description here

Here are three options to plot rasters besides the base R plot function. In the first and second options you can directly plot the raster image, while, the third requires a transformation from raster to data.frame.

rasterVis package

library(rasterVis)
gplot(image) + 
  geom_tile(aes(fill = value)) 

tmap package

library(tmap)
tm_shape(image)+ 
  tm_raster()

ggplot2 package

Finally, using ggplot2 you need to transform the raster to a data.frame and then plot it. I would not recommend this option as you need to create data frames that can be very large (and there are easier ways to get this plot).

library(ggplot2)
temp<-as.data.frame(image, xy = T)
ggplot(temp, aes(x = x, y = y, fill = image))+
  geom_raster()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM