Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 geom_tile: how to have no spacing between lines when plotting non-continuous data

Tags:

plot

r

ggplot2

I'm trying to do a levelplot using ggplot2 for a (meteorological) variable. The variable is measured continuously in time (my x-axis), but in non-continuous heights (y-axis) at every time step. The produced plot therefore shows data at the heights (y-coordinates) specified, but nothing in between. Here's an example:

library(ggplot2)
data <- runif(400, min=0, max=10)
index <- c(1:20)
heights <- c(1,2,3,4,5,7,9,12,15,19,23,28,33,39,45,52,59,67,75,83)
dat <-     as.data.frame(cbind(expand.grid(X=index,Y=heights),data))                        
ggplot(dat, aes(x=dat[,1], y=dat[,2],z=dat[,3])) +geom_tile(aes(fill=dat[,3]))

This produces the following plot: image here

Is there an easy way to fill the plot fully, i.e. make the lines in the upper part of the plot broader? Thank you!

like image 607
Cornelius Avatar asked Feb 06 '18 09:02

Cornelius


2 Answers

OK one more solution.. you could interpolate using the approx function. Although maybe 2D kriging would be more appropriate for your application???

library(purrr)
dat2<- dat %>%
  split(.$X) %>%
  map_dfr(~ approx(.$Y, .$data, xout =1:83), .id = "X") 

ggplot(dat2, aes(x=as.integer(dat2$X), y=dat2$x, z=dat2$y)) +geom_tile(aes(fill=dat2$y))

That will give you : enter image description here

like image 108
Stephen Henderson Avatar answered Oct 16 '22 13:10

Stephen Henderson


You can use the height and width attributes in geom_tile, alternatively geom_rect

library(tidyverse)
data <- runif(400, min=0, max=10)
index <- c(1:20)
heights <- c(1,2,3,4,5,7,9,12,15,19,23,28,33,39,45,52,59,67,75,83)

dat <- crossing(index = index, heights = heights) %>% 
  mutate(
    Z = data,
    index0 = index - 1) %>% 
  left_join(data_frame(heights, heights0 = c(0, heights[-length(heights)])))    

ggplot(dat, aes(xmin = index0, xmax = index, ymin = heights0, ymax = heights, fill = Z)) +
  geom_rect()

This assumes that your heights are the top of each level and that they start at zero.

enter image description here

like image 37
Richard Telford Avatar answered Oct 16 '22 13:10

Richard Telford