在ggplot中躲避间隔

时间:2015-10-13 21:55:40

标签: r ggplot2

我正在尝试使用ggplot为两个模型躲避一对平均值和置信区间。我已经查看了thisthis等类似问题,但他们的代码并没有解决我的问题。

我有以下数据框(请注意,条件是一个因素,当您沿着数据框下降时值会增加):

>print(dat)
    condition        pH    lowerH    upperH model
1   Black 650 0.7863719 0.6863438 0.8548062   pdp
2   Black 650 0.8428675 0.7123000 0.9574000   ddm
3   White 650 0.8133078 0.7310262 0.8864712   pdp
4   White 650 0.8211373 0.6838000 0.9488000   ddm
5   Black 800 0.8754109 0.7908725 0.9306012   pdp
6   Black 800 0.9408192 0.8410000 0.9941000   ddm
7   White 800 0.9044102 0.8349587 0.9623462   pdp
8   White 800 0.9183600 0.8145000 0.9867000   ddm
9   Black 950 0.9003072 0.8403200 0.9601112   pdp
10  Black 950 0.9569349 0.8812000 0.9967000   ddm
11  White 950 0.9131546 0.8494812 0.9648262   pdp
12  White 950 0.9473685 0.8683000 0.9934000   ddm
13 Black 1100 0.9091797 0.8342850 0.9622412   pdp
14 Black 1100 0.9708420 0.8864000 0.9977000   ddm
15 White 1100 0.9274862 0.8636063 0.9691300   pdp
16 White 1100 0.9570067 0.8727000 0.9954000   ddm

我试图绘制每种条件的平均值(pH)和置信区间(lowerH,upperH)作为所用模型(模型)的函数。我喜欢的是手段和CI被躲避,以便它们不重叠。我写过以下ggplot代码:

ggplot(dat, aes(x = condition, y = pH)) +
  geom_point(size = 3, shape = 5) + #pred cond mean
  geom_pointrange(aes(ymin = lowerH, ymax = upperH), size = .2) + #95% HDI
  coord_cartesian(ylim = c(.5, 1.01)) + #adjust x-axis
  ylab("Hit Rate") + #label y axis
  theme_bw() + #black and white theme
  theme(axis.title.x = element_blank(), 
    panel.background = element_blank(), 
    panel.grid = element_blank(),
    panel.border = element_rect(colour = "black", fill = NA, size = 1))

创建此输出

如您所见,两种模型的均值和CI重叠。但是,当我试图躲避它们时,正如我在下面的代码中所做的那样,我只能成功地将所有数据点移到左侧(模型均值和CI仍然重叠)。

ggplot(dat, aes(x = condition, y = pH)) +
  geom_point(size = 3, shape = 5, position = position_dodge(5)) + #pred cond mean
  geom_pointrange(aes(ymin = lowerH, ymax = upperH), size = .2) + #95% HDI
  coord_cartesian(ylim = c(.5, 1.01)) + #adjust x-axis
  ylab("Hit Rate") + #label y axis
  theme_bw() + #black and white theme
  theme(axis.title.x = element_blank(), 
    panel.background = element_blank(), 
    panel.grid = element_blank(),
    panel.border = element_rect(colour = "black", fill = NA, size = 1))

我正在寻找的是一种躲避模型手段和CI的方法,以便它们不会重叠。示例代码特别有用。

1 个答案:

答案 0 :(得分:2)

您需要为图表添加groupcolor级别。在这里我使用col,您也可以使用group来保持颜色相同:

ggplot(dat, aes(x = condition, y = pH, col = model)) +
    geom_point(size = 3, shape = 5, position = position_dodge(1)) +
    geom_pointrange(aes(ymin = lowerH, ymax = upperH), 
                    position = position_dodge(1), size = .2) 

enter image description here