使用离散轴注释ggplot(具有可重复的示例)

时间:2017-12-27 05:44:02

标签: r ggplot2

我正在努力找到一个简单的解决方案来修复我的情节。问题源于x轴的离散性质。我想用文本和段来注释该图,以显示统计结果。

1)我想在“Baby”和“Queen”之间以及“Queen”和“Worker”之间打印p值,但ggplot只允许在每个标签上方注释,不在他们之间。

2)同样,我希望将前两个geom_segments分开,但是ggplot不会让我以“Queen”-0.1之类的方式结束第一个并在“Queen”+0.1开始第二个geom_segments 因为它是混合因素和数字。

Problematic plot

以下完全可重复的示例,第12,13和18行有问题:

structure(list(zipcode = c(80123L, 80207L, 80205L, 80209L, 80206L, 
80204L, 80203L), avgLSAmount = c(643672.111111111, 815317.647058823, 
1095204.0625, 1604603.80733945, 1963074.61111111, 3282143.1372549, 
3618437.5)), .Names = c("zipcode", "avgLSAmount"), row.names = c(NA, 
-7L), class = "data.frame")

1 个答案:

答案 0 :(得分:10)

分类变量只是放置在位置1,2,3等处。如果要到达两个分类变量之间的位置,可以使用坐标,如1.2或1.5等。

这是一个可重复的示例,其中删除了所有不相关的主题代码:

data <- data.frame(Group.1 = rep(c("A", "B"), 3),
                   Group.2 = c("Baby", "Baby", "Worker", "Worker", "Queen", "Queen"),
                   value = c(0.18, 0.30, 0.09, 0.25, -0.26, -0.55))

ggplot(data, aes(y = value, x = Group.2, fill = Group.2)) +
  stat_boxplot(geom = 'errorbar') +
  geom_boxplot(notch = F, outlier.shape = NA) +
  geom_segment(aes(x=1.1, xend=1.9, y=0.7, yend=0.7)) + 
  geom_segment(aes(x=2.1, xend=2.9, y=0.7, yend=0.7)) + 
  geom_segment(aes(x=1.1, xend=2.9, y=1.2, yend=1.2)) +
  geom_point(size = 2, position = position_jitter(width = 0.2)) + 
  stat_summary(fun.y = mean, colour = "white", geom = "point", size = 4) +
  annotate("text",
           x = c(1.5, 2.5, 2),
           y = c(0.8, 0.8, 1.3),
           label = c("p < 0.001", "p < 0.001", "p = 0.89"),
           family = "", fontface = 3, size=4) + 
  scale_fill_manual(values=c("lightgreen", "darkgreen", "goldenrod1"),
                    guide = "none") +
  ylim(-1.5, 1.5) +
  labs(x="", y="Transcript expression\n(log2-centered TMM-nornalised TPMs)") +
  theme_bw()

enter image description here