Does filtering include zyour actual use case? For example:
library(tidyverse)
df = data.frame(x = 1:5, y = 1:5, z = c('a', 'a', 'a', 'b', 'b'))
ggplot(df %>% filter(z %in% z[between(x,1,2.5)]),
aes(x, y, col = z)) +
geom_line() + geom_point() +
coord_cartesian(xlim = c(1, 2.5))
, . ( , , , , .)
my_plot = function(xrng, data=df, step=0.01) {
levs = unique(data[["z"]])
n = length(levs)
dat_interp = split(data, data$z) %>%
map_df(function(d) {
x = seq(min(d$x), max(d$x), step)
data.frame(z=rep(unique(d$z), each=length(x)),
x, y=rep(approx(d$x, d$y, xout=x)$y, n))
})
ggplot(dat_interp %>% filter(z %in% z[between(x,xrng[1],xrng[2])]),
aes(x, y, col = z)) +
geom_point(data=data %>% filter(z %in% z[between(x,xrng[1],xrng[2])])) +
geom_line() +
coord_cartesian(xlim = xrng) +
scale_color_manual(values=setNames(hcl(seq(15,375,length=n+1)[1:n],100,65), levs))
}
gridExtra::grid.arrange(
my_plot(c(1,2.5)),
my_plot(c(1,4)),
my_plot(c(3,4)),
my_plot(c(4.3,6)),
my_plot(c(1.1,1.6)),
my_plot(c(4.2,4.9)))
