Reputation: 319
I've created a plot withgeom_rect
and added the annotation with geom_text_repel
but when I want to create several plots where I zoom in part of the original plot. The labels of the regions outside the zoom area also appear.
This is a minimal example:
start = c(1, 5,8, 14, 19, 25)
end =c(3, 6,12, 16, 22, 30)
label = c(1,2,3, 4, 5, 6)
library(ggplot2)
library(ggrepel)
regions = tibble::tibble(label, start, end)
ggplot() +
scale_x_continuous() +
scale_y_continuous(name = "") +
geom_rect(
data = regions,
mapping = aes(
xmin = start,
xmax = end,
ymin = 1.5,
ymax = 1.8),
color = "black",
fill = "#56B4E9"
) +
geom_text_repel(
data = regions,
aes(
x = start + (end - start) / 2,
y = 1.8,
label = label,
),
size = 10,
force_pull = 0,
nudge_y = 0.05,
direction = "x",
angle = 90,
vjust = 0,
segment.size = 0.5,
) +
ylim(1.38, 2.2) +
ylab("") +
xlab("") +
theme_minimal()
This code generates this plot:
I want to zoom into box 3, so I tried adding + xlim(8,12)
or +facet_zoom(xlim = c(8, 12))
but The zoomed plot has the annotation (labels) of box 1, box2, ... on the side as you can see here (1,2 in the right and 4,5,6 on the left of the zoomed plot)
and similar result with + xlim(8,12)
How can I remove the labels (annotation) outside the zoomed area (1,2 in the right and 4,5,6 on the left of the zoomed plot?)
Upvotes: 1
Views: 574
Reputation: 571
There are two quick fixes I can think of, where the first is the one you already mentioned. Perhaps you mistyped it, as I can run it fine.
xlim(8,12)
library(ggrepel)
start = c(1, 5,8, 14, 19, 25)
end =c(3, 6,12, 16, 22, 30)
label = c(1,2,3, 4, 5, 6)
regions = data.frame(label, start, end)
ggplot() +
scale_x_continuous() +
scale_y_continuous(name = "") +
geom_rect(
data = regions,
mapping = aes(
xmin = start,
xmax = end,
ymin = 1.5,
ymax = 1.8),
color = "black",
fill = "#56B4E9"
) +
geom_text_repel(
data = regions,
aes(
x = start + (end - start) / 2,
y = 1.8,
label = label,
),
size = 10,
force_pull = 0,
nudge_y = 0.05,
direction = "x",
angle = 90,
vjust = 0,
segment.size = 0.5,
) +
ylim(1.38, 2.2) +
xlim(8, 12) +
ylab("") +
xlab("") +
theme_minimal()
If I run this I obtain the following image
However, using
xlim()
is not always advised as it throws away all the other points which do not meet the condition. Although for your case that might be favourable.
regions
and zooming in properly using coord_cartesian()
.ggplot() +
scale_x_continuous() +
scale_y_continuous(name = "") +
geom_rect(
data = regions,
mapping = aes(
xmin = start,
xmax = end,
ymin = 1.5,
ymax = 1.8),
color = "black",
fill = "#56B4E9"
) +
geom_text_repel(
data = subset(regions, label == 3),
aes(
x = start + (end - start) / 2,
y = 1.8,
label = label,
),
size = 10,
force_pull = 0,
nudge_y = 0.05,
direction = "x",
angle = 90,
vjust = 0,
segment.size = 0.5,
) +
ylim(1.38, 2.2) +
coord_cartesian(xlim = c(8, 12)) +
ylab("") +
xlab("") +
theme_minimal()
This produces the same image (as far as I can tell)
Upvotes: 2