创建一个棒棒糖图表来比较ggplot2中的组

时间:2017-03-07 20:42:28

标签: r ggplot2

我有以下数据框

library(ggplot2)

set.seed(149)

x <- data.frame(
  region = factor(rep(1:10, each = 2)),
  group = rep(c("O", "E"), 10),
  mean = sample(1:2, 20, replace = TRUE)
)

x

   region group mean
1       1     O    2
2       1     E    1
3       2     O    1
4       2     E    2
5       3     O    1
6       3     E    1
7       4     O    1
8       4     E    1
9       5     O    1
10      5     E    2
11      6     O    2
12      6     E    2
13      7     O    1
14      7     E    1
15      8     O    1
16      8     E    1
17      9     O    1
18      9     E    2
19     10     O    1
20     10     E    1

我正在尝试创建一个棒棒糖图表,因此我可以在每个区域之间进行简单的比较(或者&#39; O&#39; E&#39;)。我做了一个哑铃情节,但很多地区的两组都是相同的,所以哑铃情节最终看起来很像点图。

这是我到目前为止所拥有的......

ggplot(x, aes(y = region, x = mean, label = mean, fill = group, colour = group)) +
  geom_segment(aes(x = 0, y = region, xend = mean, yend = region), color = "grey50", size = 0.75) +
  geom_point(size = 3) +
  geom_text(nudge_x = 1.5, angle = -45)

enter image description here

基本上,对于每个地区,我想绘制两条线,一条用于组&#39; O&#39;一组用于组&#39; E。&#39;

2 个答案:

答案 0 :(得分:4)

我们可以使用geom_linerange(“棒”),geom_point(“糖果”)以及指定position = position_dodge来完成此操作:

ggplot(x)+
    geom_linerange(aes(x = region, ymin = 0, ymax = mean, colour = group), 
                   position = position_dodge(width = 1))+
    geom_point(aes(x = region, y = mean, colour = group),
               position = position_dodge(width = 1))+
    coord_flip()

enter image description here

答案 1 :(得分:0)

Faceting也可以完成任务,当您有很多类别(即不仅是两个类别,还包括4、6等)时,该功能尤其有用

ggplot(x, aes(y = region, x = mean, label = mean, fill = group, colour = group)) +
    geom_segment(aes(x = 0, y = region, xend = mean, yend = region), color = "grey50", size = 0.75) +
    geom_point(size = 3) +
    facet_wrap(~group)

enter image description here