Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

Dynamic add geom_segment to a diagram

$
0
0

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?


Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>