0
votes

Here's a simple example of my problem. Steps are 1. create a SpatRaster (terra's version of a raster) with 10 rows, 10 columns and all cell values either 0 or 1. Step 2. Convert to a data frame and rename the columns. Step 3. Create a graph with ggplot. It uses blue and black for the colors and has a continuous legend.

library(terra)
x <- rast(nrow=10, ncol=10, xmin=0, xmax=1)
values(x) <- sample(c(0,1), replace=TRUE, size=100)
x_df <- as.data.frame(x, xy = TRUE)
names(x_df) <- c("x", "y", "value")
col1 <- c("red", "green")
g <- ggplot(data = x_df, aes(x, y,  fill = value)) +
  geom_tile()

Now I'd like to change the colors to those in col1. I have tried putting colors = col1 in the ggplot aes section and outside it, in an aes in geom_tile, and a few other options. Pretty much all return the error message Error: Aesthetics must be either length 1 or the same as the data (100): xxx.

Converting value to a factor solves one problem (the legend is now discrete 0,1) but I still can't figure out where to add code to change the default two colors.

1

1 Answers

2
votes

Try this:

g <- ggplot(data = x_df, aes(x, y)) +
  geom_tile(aes(fill = value)) + 
  scale_fill_gradient(low="red", high="green")
g