'Im encountering error in R while plotting raster
Dear fellow programmers! I am trying to plot raster using follow in R
library(raster)
library(dplyr)
library(ggplot2)
rast <- raster("HARV_dsmCrop.tif")
rast <- as.data.frame(rast, xy=TRUE)
View(rast)
ggplot()+
geom_raster(rast, aes(HARV_dsmCrop))+
scale_fill_gradientn(colours = topo.colors(10))
The code is throwing following error and the ggplot() was working fine just couple of minutes ago
Error in app$vspace(new_style$`margin-top` %||% 0) :
attempt to apply non-function
Please help!
Solution 1:[1]
You have the ggplot syntax wrong. In geom_raster the first argument should be the aesthetic mapping, whereas you have passed the data first. This is in contrast to the actual call to ggplot, where the data should be first.
Also, your call to as.data.frame means that your data is stored in three columns - an x co-ordinate, y co-ordinate and a value. These all need to be mapped to the appropriate aesthetic.
Obviously, we do not have your actual TIFF, so here is the code on an example tif which should also work for you:
library(raster)
library(dplyr)
library(ggplot2)
rast <- raster(path.expand("~/example.tif"))
rast <- as.data.frame(rast, xy = TRUE)
names(rast)[3] <- "Value"
ggplot(rast, aes(x = x, y = y, fill = Value)) +
geom_raster() +
scale_fill_gradientn(colours = topo.colors(10)) +
coord_equal() +
theme_void()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Allan Cameron |

