set.seed(16532)
df <- data.frame(
x = -10:10,
y = (-10:10)^2,
yy = (-10:10)^2 + rnorm(21, 0, 4),
yyy = (-10:10) + rnorm(21, 0, 4),
l = letters[1:21]
)
# Setting the nudging distance
ggplot(df, aes(x, y, label = l)) +
geom_line(linetype = "dotted") +
geom_point() +
geom_text(position = position_nudge_line())
ggplot(df, aes(x, y, label = l)) +
geom_line(linetype = "dotted") +
geom_point() +
geom_text_s(position = position_nudge_line())
ggplot(df, aes(x, y, label = l)) +
geom_line(linetype = "dotted") +
geom_point() +
geom_text(position = position_nudge_line(xy_relative = -0.03))
ggplot(df, aes(x, y, label = l)) +
geom_line(linetype = "dotted") +
geom_point() +
geom_text(position = position_nudge_line(x = 0.6, y = 3.2))
ggplot(df, aes(x, y, label = l)) +
geom_line(linetype = "dotted") +
geom_point() +
geom_text(position = position_nudge_line(x = -0.6, y = -4))
# Other curves, using defaults
ggplot(df, aes(x, -y, label = l)) +
geom_line(linetype = "dotted") +
geom_point() +
geom_text(position = position_nudge_line())
ggplot(subset(df, x >= 0), aes(y, sqrt(y), label = l)) +
geom_line(linetype = "dotted") +
geom_point() +
geom_text(position = position_nudge_line())
# Points scattered near a curve or line, we use 'direction = "split"'
ggplot(df, aes(x)) +
geom_line(aes(y = y), linetype = "dotted") +
geom_point(aes(y = yy)) +
geom_text(aes(y = yy, label = l),
position = position_nudge_line(direction = "split"))
ggplot(subset(df, x >= 0), aes(y, yy)) +
stat_smooth(method = "lm", formula = y ~ x) +
geom_point() +
geom_text(aes(label = l),
position = position_nudge_line(direction = "split"))
# increasing the nudging for labels near the line
ggplot(subset(df, x >= 0), aes(y, yy)) +
stat_smooth(method = "lm", formula = y ~ x) +
geom_point() +
geom_text(aes(label = l),
position = position_nudge_line(line_nudge = 2,
direction = "split"))
# fitting a linear model instead of the default spline
ggplot(subset(df, x >= 0), aes(y, yy)) +
stat_smooth(method = "lm", formula = y ~ x) +
geom_point() +
geom_text(aes(label = l),
position = position_nudge_line(method = "lm",
direction = "split"))
ggplot(subset(df, x >= 0), aes(x, x^2)) +
stat_smooth(method = "lm", formula = y ~ poly(x, 2, raw = TRUE)) +
geom_point() +
geom_text(aes(label = l),
position = position_nudge_line(method = "lm",
formula = y ~ poly(x, 2, raw = TRUE)))
Run the code above in your browser using DataLab