Reputation: 2279
This question seems difficult to understand, but to illustrate, I bring a figure as an example:
I am trying to replicate this graph. So far I've done the graphics separately, but I don't know how I can put them together as in the example.
Any help?
time <- seq(from = 0,
to = 10,
by = 0.5)
line_1 <- c(0, 0, 0, 66, 173, 426, 1440, 800, 1200, 400, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
line_2 <- c(0, 0, 0, 0, 0, 0, 0, 0, 1000, 25000, 5000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
df <- data.frame(time, line_1, line_2)
library(ggpubr)
#the plot
ggplot(data = df, aes(x = time)) +
geom_line(aes(y = line_2), color = "red",
position = position_nudge(x = 0.5, y = 1000)) +
geom_line(aes(y = line_1),color = "blue") +
geom_rect(aes(xmin = 1, xmax = 5, ymin = 0, ymax = 1500), color = "black", alpha = 0) +
theme_pubr( base_size = 8,
border = TRUE)
#The plot with a zoom
ggplot(data = df, aes(x = time, y = line_1)) +
geom_line(color = "blue") +
xlim (1, 5) +
ylim (0, 1500) +
theme_pubr( base_size = 8,
border = TRUE)
Upvotes: 7
Views: 9679
Reputation: 2262
@dww's answer inspired me to write a little package:
devtools::install_github("hughjonesd/ggmagnify")
install.packages(c("ggfx", "ggforce")
ggplot(data = df, aes(x = time)) +
geom_line(aes(y = line_2), color = "red",
position = position_nudge(x = 0.5, y = 1000)) +
geom_line(aes(y = line_1),color = "blue") +
geom_magnify(from = c(1, 0, 5, 1500),
to = c(0, 10000, 2.5, 20000),
shadow = TRUE)
Theme at will.
Upvotes: 8
Reputation: 31452
You can use a custom annotation
p1 = ggplot(data = df, aes(x = time)) +
geom_line(aes(y = line_2), color = "red", position = position_nudge(x = 0.5, y = 1000)) +
geom_line(aes(y = line_1),color = "blue") +
geom_rect(aes(xmin = 1, xmax = 5, ymin = 0, ymax = 1500), color = "black", alpha = 0) +
theme_pubr( base_size = 8, border = TRUE)
#The plot with a zoom
p2 = ggplot(data = df, aes(x = time, y = line_1)) +
geom_line(color = "blue") +
xlim (1, 5) +
ylim (0, 1500) +
theme_pubr( base_size = 8,border = TRUE)
p1 +
annotation_custom(ggplotGrob(p2), xmin = 0, xmax = 4, ymin = 5000, ymax = 20000) +
geom_rect(aes(xmin = 0, xmax = 4, ymin = 5000, ymax = 20000), color='black', linetype='dashed', alpha=0) +
geom_path(aes(x,y,group=grp),
data=data.frame(x = c(1,0,5,4), y=c(1500,5000,1500,5000),grp=c(1,1,2,2)),
linetype='dashed')
Upvotes: 15