I am using R to solve an equation with two variables in R. I am varying the two variables by a sequence and then using geom_raster with interpolation to generate a plot of solutions.
However, when I plot the data I noticed that the plot area exceeds the range of the y-axis values that I give as input.
If I use ylim to impose a limit on the area, then the interpolated plot shrinks and no longer bounds the values. If I use vjust = 0, then the top of the plot bounds the area, but the bottom does not.
My code for a reproducible example is as follows:
library(ggplot2)
library(reshape2)
x_range <- seq(0.001,10, by=0.001)
y_range <- (seq(1*10^-10, 1*10^-9, by = 1*10^-10))
FUN <- function(x, y) log10((1)/(x*y))
data <- outer(x_range, y_range, FUN)
colnames(data) <- y_range
rownames(data) <- x_range
melted_data <- melt(data)
p <- ggplot(data=melted_data)
# basic plot
p + geom_raster(aes(x=Var1, y=Var2, fill=value), interpolate = TRUE) +
geom_hline(yintercept = 1*10^-10) +
geom_hline(yintercept = 1*10^-9)
# with imposed ylim
p + geom_raster(aes(x=Var1, y=Var2, fill=value), interpolate = TRUE) +
geom_hline(yintercept = 1*10^-10) +
geom_hline(yintercept = 1*10^-9) +
ylim(1*10^-9, 1*10^-10)
# with modified vjust
p + geom_raster(aes(x=Var1, y=Var2, fill=value), interpolate = TRUE, vjust = 0) +
geom_hline(yintercept = 1*10^-10) +
geom_hline(yintercept = 1*10^-9)
I would like the final plot to bound the actual data given (specified by the two horizontal lines at y = 1*10^-9 and y = 1*10^-10.
I think what I am observing is due to the interpolated pixel size, but I am not sure.
I think this has nothing to do with interpolation, & everything to do with the fact that geom_raster
(a special case of geom_tile
) by default uses x
/ y
as the center of each tile. Specifying vjust = 1
shifts the tiles downwards, but the idea is still the same. What you see beyond the limits imposed by geom_hline
are the top half of the 1st row of tiles & bottom half of the last row of tiles.
If you don't want to show these half-tiles, you can set your y-axis limits in coord_cartesian
rather than ylim
(this applies the limit to the coordinate system, rather than the scale; see ?coord_cartesian
for further details) to zoom in to the specific data range:
p + geom_raster(aes(x=Var1, y=Var2, fill=value), interpolate = TRUE) +
# limit coordinate system, without expansion
coord_cartesian(ylim = c(1*10^-10, 1*10^-9), expand = FALSE)
Alternatively if you have other geom layers that extend beyond c(1*10^-10, 1*10^-9)
& don't want to zoom, you can add a masking layer to cover the half-tiles:
p + geom_raster(aes(x=Var1, y=Var2, fill=value), interpolate = TRUE) +
# add masking layers
annotate(geom = "rect", xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = 1*10^-10, fill = "white") +
annotate(geom = "rect", xmin = -Inf, xmax = Inf, ymin = 1*10^-9, ymax = Inf, fill = "white")
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