1

I have a dataframe like this

library(ggplot2)
df = data.frame(N = c(12, 18))

And I want to get

enter image description here

I do

ggplot()+ geom_segment(aes(x = 0, y = 0.5, xend = max(df$N), yend =0.5), color="grey50", 
                       linetype="dashed", size=1.5) + 
  geom_segment(aes(x = df$N[1], y = 0, xend = df$N[1], yend = 0.5), color="grey50", 
               linetype="dashed", size=1.5)+
 geom_segment(aes(x = df$N[2], y = 0, xend = df$N[2], yend = 0.5), color="grey50", 
               linetype="dashed", size=1.5)

The problem is that the data can change, the rows can be not two, but three or more, and the code becomes incorrect. So I try to use a loop

v = list()
for (i in 1:length(df$N)) {
  n = geom_segment(aes(x = df$N[i], y = 0, xend = df$N[i], yend = 0.5), color="grey50", 
                   linetype="dashed", size=1.5)
  v = append(n, v)
}
v
ggplot()+ geom_segment(aes(x = 0, y = 0.5, xend = max(df$N), yend =0.5), color="grey50", 
                       linetype="dashed", size=1.5) + v 

But the diagram only shows the last line. How to fix the loop or I have to do another way?

1 Answer 1

2

You don't need a loop; geom_segment can handle multiple inputs from a vector.

df1 <- data.frame(N = c(12, 18, 24))

library(ggplot2)

ggplot(data = df1)+ 
  geom_segment(aes(x = 0, y = 0.5, xend = max(N), yend =0.5), 
                color="grey50", linetype="dashed", size=1.5) + 
  geom_segment(aes(x = N, y = 0, xend = N, yend = 0.5), 
                color="grey50", linetype="dashed", size=1.5)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.