Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding different geom_segment to every facet

Tags:

r

ggplot2

I have the code below, and it works fine. The problem is, I would like to add "k" and plot a straight line similar to "z", but "k" is a vector of different numbers. Each element in "k" should be plotted as a line on the 3 facets created. If k was a singular value, I would just repeat the geom_segment() command with different y limits. Is there an easy way to do this? The final output should look like attached, assuming I could draw straight lines.

x <- iris[-1:-3]
bw <- 1
nbin <- 100
y <- head(iris, 50)[2]
z <- 1
k <- c(2, 3, 4)
    
ggplot(x, aes(x = Petal.Width)) +
  geom_density(aes(y = bw *..count.., fill = Species), size = 1, alpha = 0.4) + 
  geom_segment(aes(x = 5, y = 250, xend = z, yend = 250, color = "red")) +
  facet_wrap(~Species)+
  scale_x_continuous(labels = scales::math_format(10^.x), limits = c(0, 5), expand = c(0,0)) + 
  scale_y_continuous(expand = c(0,0), limits = c(0, NA)) +
  annotation_logticks(sides = "b", short=unit(-1,"mm"), mid=unit(-2,"mm"), long=unit(-3,"mm")) +
  coord_cartesian(clip='off') + theme(panel.background = element_blank(), 
                                      panel.border = element_rect(colour = "black", fill=NA)) 

enter image description here

like image 841
user13589693 Avatar asked Sep 06 '25 13:09

user13589693


1 Answers

you can try this. Assuming that your plot is saved as p1.

k_data = data.frame(k, Species = levels(x$Species))
p1 + geom_segment(data = k_data, aes(x =5, y = 200, xend = k, yend = 200), 
                  color = "blue", inherit.aes = F)  

enter image description here

The idea is to create a dataframe with the columns k and Species and use this data exclusivley in a geom by setting inherit.aes = F

like image 76
Roman Avatar answered Sep 08 '25 03:09

Roman