问题
In the plot below I'd like to move the label "V-Engine" into the plot margin. Adjusting the nudge_x
argument is moving the "S-Engine" label but not the "V-Engine" label.
library(ggplot2)
library(ggrepel)
library(dplyr)
ds <-
mtcars %>%
mutate(vs = factor(vs, labels = c("V-Engine", "S-Engine"))) %>%
# Create labels for the rightmost data points
group_by(vs) %>%
mutate(
label =
case_when(
wt == max(wt) ~ as.character(vs),
TRUE ~ NA_character_
)
) %>%
ungroup()
ds %>%
ggplot(aes(x = wt, y = mpg, color = vs)) +
geom_smooth(se=FALSE) +
geom_label_repel(aes(label = label), nudge_x = 1, na.rm = TRUE) +
guides(color = FALSE) +
theme_minimal() +
theme(plot.margin = unit(c(1,3,1,1), "cm"))
回答1:
You can set xlim()
inside geom_label_repel
library(dplyr)
library(ggplot2)
library(ggrepel)
ds %>%
ggplot(aes(x = wt, y = mpg, color = vs)) +
geom_smooth(se=FALSE) +
geom_label_repel(aes(label = label),
nudge_x = 1,
# direction = 'x',
xlim = c(0, 6.5),
na.rm = TRUE) +
guides(color = FALSE) +
theme_minimal() +
theme(plot.margin = unit(c(1,3,1,1), "cm")) +
coord_cartesian(clip = 'off')
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'
Created on 2018-11-16 by the reprex package (v0.2.1.9000)
来源:https://stackoverflow.com/questions/53346606/move-labels-from-geom-label-repel-into-ggplot-margin