ggplot2: raster plotting does not work as expected when setting alpha values

浪尽此生 提交于 2019-12-02 21:58:58

Q1: You can't have different fill scales on different layers. One workaround is to use the fill aesthetic for the DEM and the alpha aesthetic for hillshade. Unfortunately, geom_raster doesn't seem to use the alpha aesthetic the way I expected. You can get the same effect with geom_tile, it just takes longer:

ggplot(hdf) +
  geom_raster(data=ddf,aes(X,Y,fill=DEM)) +
  scale_fill_gradientn(name="Altitude",colours = rainbow(100),breaks=b.dem) +
  geom_tile(aes(X,Y,alpha=Hill), fill = "grey20") +
  scale_alpha(range = c(0, 0.5)) +
  scale_x_continuous(name=expression(paste("Longitude (",degree,")")),
    limits=c(-4,2),expand=c(0,0)) +
  scale_y_continuous(name=expression(paste("Latitude (",degree,")")),
    limits=c(4,12),expand=c(0,0)) +
  coord_equal() 

Q2: Check out ?guide_colorbar. It doesn't work very nicely with your 100 colour breaks, but with fewer it's pretty good.

ggplot(hdf)+
  geom_raster(data=ddf,aes(X,Y,fill=DEM))+
  scale_fill_gradientn(name="Altitude",colours = rainbow(20))+
  guides(fill = guide_colorbar()) +
  geom_tile(aes(X,Y,alpha=Hill), fill = "grey20") +
  scale_alpha(range = c(0, 0.5)) +
  scale_x_continuous(name=expression(paste("Longitude (",degree,")")),
    limits=c(-4,2),expand=c(0,0)) +
  scale_y_continuous(name=expression(paste("Latitude (",degree,")")),
    limits=c(4,12),expand=c(0,0)) +
  coord_equal() 

The alpha in raster will be supported in the next version, so you can draw by:

ggplot(NULL, aes(X, Y)) + 
  geom_raster(data = ddf, aes(fill = DEM)) + 
  geom_raster(data = hdf, aes(alpha = Hill)) +
  scale_fill_gradientn(name="Altitude",colours = rainbow(20))+
  guides(fill = guide_colorbar()) +
  scale_alpha(range = c(0, 0.5), guide = "none") +
  scale_x_continuous(name=expression(paste("Longitude (",degree,")")), limits=c(-4,2),expand=c(0,0)) +
  scale_y_continuous(name=expression(paste("Latitude (",degree,")")), limits=c(4,12),expand=c(0,0)) +
  coord_equal()

anyway, very beautiful plot.

If you want to use this immediately, try installing from github:

library(devtools)
install_github("ggplot2", "kohske", "fix/geom-raster-alpha")

Note that geom_tile and geom_raster look different in some devices. Perhaps raster is better for your purpose.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!