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:
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!
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 :
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With