user13589693
user13589693

Reputation: 369

Adding different geom_segment to every facet

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

Upvotes: 4

Views: 1300

Answers (2)

Roman
Roman

Reputation: 17648

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

Upvotes: 2

Rui Barradas
Rui Barradas

Reputation: 76460

In this solution, the value of k is made part of the data set being plotted through a pipe. It is a temporary modification of the data set, since it is not assigned back to it nor to any other data set.

library(ggplot2)
library(dplyr)

x <- iris[-1:-3]
str(x)
bw <- 1
nbin <- 100
y <- head(iris, 50)[2]
z <- 1
k <- c(2, 3, 4)

x %>%
  mutate(k = rep(k, each = 50)) %>%
  ggplot(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") +
  geom_segment(aes(x = 5, y = 200, xend = k, yend = 200), color = "blue") +
  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

Upvotes: 0

Related Questions