Grouped data by factor with geom_segment

2019-07-14 21:20发布

I would like to show clusters of segments by factor groups using geom_segment but the position parameter doesn't seem to be doing anything. Here's an example:

mydata = data.frame(variable = factor(c("A","A","A","B","C")),
                    color = factor(c(1,2,3,4,5)),
                    start = c(1,2,1,4,6),
                    end = c(3,4,6,5,8))

ggplot(mydata, aes(x = start, xend = end, y = variable, yend = variable)) + 
  geom_segment(aes(color = color, position = "stack"), size = 3)

enter image description here

I've also tried position = "dodge". Group A should have 3 segments, but they're all covered up by the green bar. Adjusting the transparency will be too confusing visually. How can I make sure that all the segments for each factor show up side-by-side?

标签: r ggplot2
1条回答
Lonely孤独者°
2楼-- · 2019-07-14 21:37

I'm a little uncertain that @alistaire and I are communicating this clearly to you, so here's what we mean:

mydata = data.frame(variable = factor(c("A","A","A","B","C")),
                                        color = factor(c(1,2,3,4,5)),
                                        start = c(1,2,1,4,6),
                                        end = c(3,4,6,5,8))

ggplot(mydata, aes(ymin = start, ymax = end, x = variable)) + 
    geom_linerange(aes(color = color),position = position_dodge(width = 0.2), size = 3) + 
    coord_flip()

Which results in:

enter image description here

查看更多
登录 后发表回答