Reputation: 7938
I want to draw a segment below a density plot and I would like to have the distance be a constant number of pixels. Is this possible? I Know how to hardcode the distance. For example:
set.seed(40816)
library(ggplot2)
df.plot <- data.frame(x = rnorm(100, 0, 1))
ggplot(df.plot, aes(x = x)) + geom_density() +
geom_segment(aes(x = -1, y = -0.05, xend = 1, yend = -0.05),
linetype = "longdash")
produces :
But
df.plot <- data.frame(x = rnorm(100, 0, 4))
ggplot(df.plot, aes(x = x)) + geom_density() +
geom_segment(aes(x = -1, y = -0.025, xend = 1, yend = -0.025),
linetype = "longdash")
produces a plot with the segment much further away from the density
Upvotes: 0
Views: 281
Reputation: 77096
You could use annotation_grob,
set.seed(40816)
library(ggplot2)
df.plot <- data.frame(x = rnorm(100, 0, 1))
strainerGrob <- function(pos=unit(2,"mm"), gp=gpar(lty=2, lwd=2))
segmentsGrob(0, unit(1,"npc") - pos, 1, unit(1,"npc") - pos, gp=gp)
ggplot(df.plot, aes(x = x)) + geom_density() +
annotation_custom(strainerGrob(), xmin = -1, xmax = 1, ymin=-Inf, ymax=0) +
expand_limits(y=-0.1)
Upvotes: 2