在ggplot(facet_wrap和position_nudge)中使用并排的微移图时出错

时间:2017-08-22 03:18:12

标签: r ggplot2

我正在尝试使用ggplot创建R中带有轻微数据点(优势比,95%CI误差条)的并排图。每次我尝试组合它们都会出错。任何人都可以帮我确定我应该做些什么来改变我的代码?这是我得到的错误:

  

(~surx)+ scale_x_continuous(breaks = seq(0,4,1))中的错误:     二元运算符的非数字参数

为了说明我正在尝试做什么,请参阅下面我使用plot()创建的版本,你可以看到它是相当丑陋的:Example of plot I want to create using ggplot我已经尝试根据指导结合facet_wrap和position_nudge在J Stuart Carlton博客中,但未能添加position_nudge。上面的错误代码表明问题出在我的代码的facet_wrap部分。 enter image description here

我在下面介绍了如何复制数据集的代码。

activity <- factor(rep(c("Good interaction", "Poor interaction",
                              "RTW plan"), times = 4))
surv <- factor(rep(c("T1", "T2"), each = 3, times = 2))
mod <- factor(rep(c("Crude", "Adjusted"), each = 6))
or <- c(1.72, 1.26, 2.39, 2.5, 1.34, 1.89, 1.14, 1.09, 2.02, 1.9, 1.1, 1.02)
low <- c(1.22, 0.74, 1.73, 1.74, 0.61, 1.35, 0.77, 0.61, 1.40, 1.22, 0.60, 0.68)
hi <- c(2.41, 2.16, 3.29, 3.6, 1.8, 2.64, 1.70, 1.94, 2.90, 2.95, 2.04, 1.54)
rtwc <- data.frame(activity, surv, mod, or, low, hi)

这是我一直在使用的ggplot代码:

ggplot(rtwc, aes(x = or, y = activity, colour = mod)) +
  geom_vline(aes(xintercept = 1), size = 0.25, linetype = "dashed") +
  geom_errorbarh(data = filter(rtwc, mod == "crude"), aes(xmax = hi, xmin = low), size = 0.5, height = 0.1, colour = "gray50", position = position_nudge(y = fix)) + 
  geom_point(data = filter(rtwc, mod == "crude"), aes(xmax = hi, xmin = low), size = 4, position_nudge(y = fix)) + 
  geom_errorbarh(data = filter(rtwc, mod == "Adjusted"), aes(xmax = hi, xmin = low), size = 0.5, height = 0.1, colour = "gray50", position = position_nudge(y = -fix)) + 
  geom_point(data = filter(rtwc, mod == "Adjusted"), size = 4, position = position_nudge(y = -fix)) +   
  geom_errorbarh(data = filter(rtwc, mod = "Adjusted")) + 
  facet_wrap = (~surv) +
  scale_x_continuous(breaks = seq(0, 4, 1)) + 
  coord_trans(x = "log10") +
  theme_bw() +
  theme(panel.grid.minor = element_blank())

如果此问题上已有帖子,请道歉。

1 个答案:

答案 0 :(得分:0)

以下是一些可以帮助您入门的代码。我使用position_dodgecoord_flip一起使错误条对彼此远离:

ggplot(rtwc,
       aes(y = or, ymin = low, ymax = hi, x = activity, group = mod)) +
  geom_hline(yintercept = 1, size = 0.25, linetype = "dashed", colour = "grey") +
  geom_errorbar(width = 0.2, position = position_dodge(0.5)) +
  geom_point(aes(col = mod), position = position_dodge(0.5),
             size = 3) +
  scale_x_discrete(name = "") +
  scale_y_log10(name = "", breaks = seq(0, 4)) +
  scale_color_manual(name = "", values = c("red", "blue")) + # change colours here
  expand_limits(y = c(0.1, 4)) + #adjust x axis range here
  facet_wrap(~surv) +
  coord_flip() + 
  theme_bw() + #change look & feel here
  theme(panel.grid.minor = element_blank())

coefficient plot

调整情节的外观&amp;您可以查看ggplot here中的可用主题,&amp; ggthemes here中的更多主题。请不要使用Excel 2013主题。正如创作者所指出的那样,它的存在只是为了讽刺目的。

对于点颜色的调整,这里的名称为handy reference颜色。或者您可以使用RColorBrewer中的一个调色板,可以通过RColorBrewer::display.brewer.all()查看。