Enriching a ggplot2 plot with multiple geom_segment in a loop?

前端 未结 2 1231
花落未央
花落未央 2020-12-17 23:08

I successfully create a plot using the following:

# suppose I have a p <- ggplot(data=df, ...) then the following works 
# I get those two segments plotte         


        
2条回答
  •  失恋的感觉
    2020-12-17 23:17

    An alternative approach would be to avoid using a loop at all. You can pack your segment data up in a separate data.frame from your main data and use aes() to plot everything at once like so:

    segment_data = data.frame(
        x = c(1, 5),
        xend = c(1, 5), 
        y = c(103, 103),
        yend = c(107, 107)
    )
    
    p = ggplot(df, ...) +
    geom_segment(data = segment_data, aes(x = x, y = y, xend = xend, yend = yend))
    

提交回复
热议问题