如何避免ggplot2中的重叠图

时间:2015-08-27 12:27:25

标签: r plot ggplot2

我想通过两次曝光(世博会)绘制三个年龄组(agecat)的估计值。下面的代码生成重叠的图表,按字母顺序重新排列年龄组。我怎样才能避免情节的重叠和情节维持年龄组的现有顺序? 我用了这段代码:

ggplot(mydf, aes(x = agecat, y = est,ymin = lcl, ymax = ucl,  group=agecat,color=agecat,shape=agecat))  +
  geom_point(position="dodge",size = 4) +
  geom_linerange(position="dodge",size =0.7) +
  geom_hline(aes(yintercept = 0))  + 
  labs(colour="Age Group", shape="Age Group") +    theme(axis.title=element_text(face="bold",size="12"),axis.text=element_text(size=12,face="bold")) 

enter image description here 样本数据:

 > dput(mydf)
    structure(list(expo = c(0, 1, 0, 1, 0, 1), est = c(0.290780632898979, 
    0.208093573361601, 0.140524761247529, 0.156713614649751, 0.444402395010579, 
    0.711469870845916), lcl = c(0.0679784035303221, -0.00413163014975071, 
    -0.208866152400888, -0.175393089838871, -0.227660022186016, 0.0755871550441212
    ), ucl = c(0.514078933380535, 0.420769190852455, 0.491138970050864, 
    0.489925205664665, 1.12099179726843, 1.35139300089608), agecat = c("young", 
    "young", "middle", "middle", "old", "old")), .Names = c("expo", 
    "est", "lcl", "ucl", "agecat"), row.names = c(2L, 4L, 6L, 8L, 
    10L, 12L), class = "data.frame")

2 个答案:

答案 0 :(得分:2)

我会通过在图中使用expo作为变量来完成此操作。这会让ggplot知道你有重叠,所以你需要避开x变量的每个级别。完成此操作后,您可以直接在两个geom中使用position = position_dodge(),并将width参数设置为您想要的任何内容。有关何时需要明确设置position_dodge的示例,请参阅width的帮助页面。

此处,我将group = agecat替换为group = expo。使用group代替shape之类的美学意味着没有任何迹象表明哪个点代表图形上的expo级别。

mydf$agecat = factor(mydf$agecat, levels = c("young", "middle", "old"))

ggplot(mydf, aes(x = agecat, y = est, ymin = lcl, ymax = ucl,  group = expo, color = agecat, shape = agecat))  +
    geom_point(position = position_dodge(width = .5), size = 4) +
    geom_linerange(position = position_dodge(width = .5), size = 0.7) +
    geom_hline(aes(yintercept = 0))  + 
    labs(colour="Age Group", shape="Age Group") +    
    theme(axis.title = element_text(face="bold", size="12"),
          axis.text = element_text(size=12, face="bold"))

enter image description here

答案 1 :(得分:0)

您可以将列agecat转换为具有所需顺序的级别的因子。然后,正如Heroka在评论中指出的那样,我们可以使用facet_wrap来实现类似的效果:

mydf$agecat <-  factor(mydf$agecat, levels=c("young", "middle", "old"))
ggplot(mydf, aes(x = agecat, y = est, ymin = lcl, ymax = ucl, group=agecat,color=agecat, shape=agecat))  + 
  geom_linerange(size =0.7) +
  geom_hline(aes(yintercept = 0))  + labs(colour="Age Group", shape="Age Group") + 
  facet_wrap(agecat~est,  scales="free_x", ncol=6) + geom_point(size = 4)+  theme(axis.title=element_text(face="bold",size="12"),axis.text=element_text(size=12,face="bold"),strip.text.x = element_blank())

enter image description here