按geom_segment的因子分组数据

时间:2016-02-10 18:17:00

标签: r ggplot2

我想使用geom_segment按因子组显示细分群集,但position参数似乎没有做任何事情。这是一个例子:

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

我也试过position = "dodge"。 A组应该有3个部分,但它们都被绿色条所掩盖。调整透明度在视觉上会太混乱。如何确保每个因素的所有段都并排显示?

1 个答案:

答案 0 :(得分:4)

我有点不确定@alistaire和我正在清楚地向你传达这一点,所以这就是我们的意思:

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()

结果是:

enter image description here