I often found I want to zoom in a ggplot2
plot interactively.
- There is svgPanZoom but that is just like zoom in on a static picture, you will not see additional details.
- There is
ggplot2
extension mechanism. But I don't want to add moregeom
functions. I want to take anyggplot2
you just made and add zoom control to it.
Now you can create your plot and feed it to one function, then a Shiny app will be launched with your plot. Use mouse to draw a box, then double click to zoom in. Double click anywhere to reset the zoom.
source("gg_zoom.R")
x <- 1:1000
y <- runif(length(x), 0,10)
df <- data.frame(x = x, y = y)
g <- ggplot(df, aes(x,y)) +
geom_point()
gg_zoom_m(g)
# it will detect the axis type of date/date time and apply conversion function needed automatically. This need the lubridate package.
x <- seq(as_date("2000/01/01"), as_date("2000/06/01"), by = "day")
y <- runif(length(x), 0,10)
df <- data.frame(x = x, y = y)
g <- ggplot(df, aes(x,y)) +
geom_point()
gg_zoom(g)
x <- seq(ymd_hms("2000/01/01 00:00:01"), ymd_hms("2000/02/01 11:59:59"), by = "hour")
y <- runif(length(x), 0,10)
df <- data.frame(x = x, y = y)
g <- ggplot(df, aes(x,y)) +
geom_point()
gg_zoom(g)
I tried ggplot() %>% gg_zoom()
but that doesn't work, so you still need to save the ggplot object first.
Because of the implementation, it's possible that the zoom may override the fixed aspect ratio or xlim/ylim specified in original plot.