ggplot a color for each value

Viewed 37

I have a spatial dataset, containing values from 0 to 10. I want every number (11 numbers) to have a unique color from a gradient. The simple plot function does the trick (assigning one color to one value) but my default is ggplot, which I also want to use here. ggplot only uses ten colors for some reason and I cannot figure out why. I think I might just be using the wrong scale_x_y function.

Reproducible example:

#Colors
cols <- colorRampPalette(c("white", "yellow", "red", "darkred"))


# Create Raster
r <- raster(ncol=100, nrow=100)
r[] <- sample(0:10, 10000, replace = T)

# Plot simple
plot(r, col=cols(11))



# Convert to df
r <- as.data.frame(r, xy=T)


# Plot with ggplot
X <- ggplot(data = r) + geom_raster(aes(x = x, y = y, fill = layer), interpolate = F) + 
        scale_fill_stepsn(colors=cols(11), breaks=seq(0,10,1), show.limits=T)
print(X)

EDIT: ggplot only using 10 colors instead of 11 becomes more clear when not including white:

cols <- colorRampPalette(c("yellow", "red", "darkred", "black"))
0 Answers
Related