r - Convex hull on horizontal and vertical error bars
问题描述
I have a ggplot with means and both horizontal and vertical error bars, and I'd like to add a convex hull that encompasses all the error bars - like so:
I have tried with stat_chull
from ggpubr
but am not sure how to specify the aesthetics when there is a xmin
, xmax
, ymin
and ymax
for the error bars of each point. Below is how I coded the plot specifying the stat_chull
aes
as the X and Y means as an example - I know this is incorrect but I think I am on the right track?
ggplot()+
geom_point(data = df, aes(MeanX,MeanY)) +
geom_errorbar(data = df,
mapping = aes(x = MeanX,
ymin = MeanY - SdY,
ymax = MeanY + SdY),
width = 0, inherit.aes = FALSE)+
geom_errorbarh(data = df,
mapping = aes(y = MeanY,
xmin = MeanX - SdX,
xmax = MeanX + SdX),
height = 0, inherit.aes = FALSE)+
stat_chull(data = df, aes(MeanX,MeanY))+
theme_classic()
This gives the following plot:
I have also tried geom_polygon and got garbage.
Here is a the data:
df<-structure(list(Source = structure(1:5, .Label = c("A", "B", "C", "D",
"E"), class = "factor"), MeanX = c(-18.7066666666667,
-15.8769230769231, -16.8620689655172, -15.72, -17.4333333333333
), SdX = c(1.61072554509115, 0.409201849758959, 1.04811067886951,
0.74057035077327, 1.15902257671425), MeanY = c(9.93666666666667,
14.3230769230769, 9.22758620689655, 11.1, 13.7333333333333),
SdY = c(1.03005970142791, 0.539116085686704, 0.504990221704281,
0.757187779440037, 1.05039675043925)), row.names = c(NA,
-5L), class = "data.frame")
Any help is greatly appreciated!
解决方案
Does the following work for you?
library(dplyr)
df %>%
mutate(ymin = MeanY - SdY,
ymax = MeanY + SdY,
xmin = MeanX - SdX,
xmax = MeanX + SdX) %>%
ggplot(aes(x = MeanX, y = MeanY))+
geom_point() +
geom_errorbar(aes(ymin = ymin, ymax = ymax),
width = 0)+
geom_errorbarh(aes(xmin = xmin, xmax = xmax),
height = 0)+
stat_chull(data = . %>%
summarise(x = c(MeanX, MeanX, MeanX, xmin, xmax),
y = c(MeanY, ymin, ymax, MeanY, MeanY)),
aes(x = x, y = y),
geom = "polygon", colour = "black", fill = NA)+
theme_classic()
推荐阅读
- r - 如何将股票代码读入函数?
- c++ - C++ - 将二维数组传递给函数
- python - 使用json标签水平翻转数据集中图像的简单方法?
- php - 使用数据表时,具有一列复选框的表格显示被隐藏
- amazon-ecs - 如何从 Docker 实例内部将多个日志流式传输到 AWS CloudWatch?
- python - 根据 'key=value' 项将 pandas 列拆分为多个列
- jetbrains-ide - 如何在 JetBrains Marketplace 准入期间配置插件验证程序?
- python - 尽管安装了两个模型,但没有名为“pandas”、“mysql”的模块
- installshield - 如何在 InstallShield 脚本中读取命令行参数
- .net - 在 .NET Framework 应用程序中为 .NET Core 应用程序创建虚拟目录