r - 使用 R 向 ggplot2 中的绘图添加带箭头的单箭头

标签 r plot

我有一台 64 位的 PC。在 Rstudio v0.98.953 中使用 ggplot 2,当前 R 更新。

我是 ggplot 的新手,对 R 的熟练程度有限。我有以下代码:

# Simple Bar Plot for Multivariate OR by NVP quartile
dat <- data.frame(
  QUAR = factor(c("1","2","3","4"), levels=c("1","2","3","4")),
  aOR = c(1.00, 2.47, 3.33, 9.17),
  lowerCI = c(1.00, 1.09, 1.33, 3.20),
  upperCI = c(1.00, 5.60, 8.30, 26.0)
)
dat

library(ggplot2)
myplot = ggplot(data=dat, aes(x=QUAR, y=aOR, fill=QUAR)) + 
  geom_bar(colour="black", width=.8, stat="identity") + 
  scale_fill_manual(values=c("#e8e7e7", "#c3bfbf", "#908c8c", "#363434")) +
  guides(fill=FALSE) +
  xlab("XXX Quartile") + ylab("YYY") +
  geom_text(data=dat, aes(x=QUAR, y=aOR, label=round(aOR, 1)), vjust=-0.5) +
  coord_cartesian(ylim = c(0, 11)) +
  ggtitle("Graph")
myplot
# this gets rid of the grid line and background color  
plot (myplot)  
myplot2 = myplot + geom_errorbar(aes(ymin=lowerCI, ymax=upperCI), width=.1) +
       theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"))
myplot2

enter image description here

这工作正常,但我想在第 4 个栏上添加一个箭头。您可以看到 CI 超出了 Y 轴的上限(设置为 11),我只想放一个指向上方的箭头以指示第 4 个柱的上限超出 11。

我试过箭头函数 - arrows(x0, y0, x1, y1, code=1),但无法让它运行(没有调用 plot.new 返回或类似的东西)。

有什么想法吗?

谢谢!

最佳答案

geom_segment 有一个 arrow应该在这里帮助你的论点。尝试这样的事情:

library(grid)  ## Needed for `arrow()`

myplot2 + geom_segment(aes(x=4, xend=4, y=10, yend=11), 
                           arrow = arrow(length = unit(0.5, "cm")))

enter image description here

关于r - 使用 R 向 ggplot2 中的绘图添加带箭头的单箭头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29310581/

相关文章:

r - R 新手, "unexpected symbol error"由拼写错误引起

r - 将化石尖端添加到树上

r - 如何将 2D 数据框转换为 3D 矩阵,保留行和列顺序

r - ggplot2:来自 alpha 的颜色不一致

plot - gnuplot:如何将绘图区域设置为数据的像素完美表示

r - 从 Perl 执行 R 脚本

r - 西类牙语月份名称的数字

r - 生成漂亮的线性回归图(拟合线、置信度/预测带等)

从 ggplot 图例中删除单个标签

python - 流图错误 : Cannot convert float NaN to integer