geom_raster interpolation with log scale

前端 未结 1 1274
遇见更好的自我
遇见更好的自我 2021-01-06 03:31

I\'m a bit stuck plotting a raster with a log scale. Consider this plot for example:

ggplot(faithfuld, aes(waiting, eruptions)) +
 geom_raster(aes(fill = den         


        
相关标签:
1条回答
  • The dataset faithfuld already have a column for density which is the estimates of the 2D density for waiting and eruptions. You can find that the eruptions and waiting in the dataset are points in a grid. When you use geom_raster, it doesn't compute the density for you. Instead, it plots the density according to the x, y coordinates, in this case, is the grid. Hence, if you just apply the log transformation on y, it will distort the difference between y (originally they are equally spaced) and this is why you see the space in your plot. I used points to visualize the effects:

    library(ggplot2)
    library(gridExtra)
    
    # Use point to visualize the effect of log on the dataset
    g1 <- ggplot(faithfuld, aes(x=waiting, y=eruptions)) +
      geom_point(size=0.5)    
    
    g2 <- ggplot(faithfuld, aes(x=waiting, y=log(eruptions))) +
      geom_point(size=0.5)    
    
    grid.arrange(g1, g2, ncol=2)    
    

    If you really want to transform y to log scale and produce the density plot, you have to use the faithful dataset with geom_density_2d.

    # Use geom_density_2d
    ggplot(faithful, aes(x=waiting, y=log(eruptions))) +
      geom_density_2d() +
      stat_density_2d(geom="raster", aes(fill=..density..),
                      contour=FALSE)
    

    Update: Use geom_rect and supply custom xmin, xmax, ymin, ymax values to fit the spaces of the log scale.

    Since the geom_raster use the same size of tiles, you probably have to use geom_tile or geom_rect to create the plot. My idea is to calculate how large (width) each tile should be and adjust the xmin and xmax for each tile to fill up the gap.

     dat <- data.frame(x = rep(1:10, 10), 
                      y = unlist(lapply(1:10, function(i) rep(i, 10))), 
                      z = faithfuld$density[1:100])
    library(ggplot2)
    library(gridExtra)   
    
    g <- ggplot(dat, aes(x = log(x), y = y, fill = z)) +
      geom_raster()   
    
    # Replace the ymin and ymax
    distance <- diff((unique(dat$x)))/2
    upper <- (unique(dat$x)) + c(distance, distance[length(distance)])
    lower <- (unique(dat$x)) - c(distance[1], distance) 
    
    # Create xmin, xmax, ymin, ymax
    dat$xmin <- dat$x - 0.5 # default of geom_raster is 0.5
    dat$xmax <- dat$x + 0.5
    dat$ymin <- unlist(lapply(lower, function(i) rep(i, rle(dat$y)$lengths[1])))
    dat$ymax <- unlist(lapply(upper, function(i) rep(i, rle(dat$y)$lengths[1])))        
    
    # You can also use geom_tile with the width argument
    g2 <- ggplot(dat, aes(x=log(x), y=y, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, fill=z)) +
      geom_rect() 
    
    # show the plots     
    grid.arrange(g, g2, ncol=2)
    

    0 讨论(0)
提交回复
热议问题