R ggplot:如何创建带有边缘箱线图的散点图

R ggplot: How to create a scatter plot with marginal box plots

我的数据是这样的:

d1 <- read.table(header = TRUE, text =                   
                   "a1c   att  status
                 8.500000 23.58333  case
                 8.450000 12.25000 control
                 8.266667 18.91667 control")

a1c   att  status
1  8.500000 23.58333  case
2  8.450000 12.25000 control
12 8.266667 18.91667 control

我想绘制 a1catt 联合分布的箱线图(比如 x 轴上的 a1c 和 y 轴上的 att),箱线图中的点由 [=14= 着色] 在第 3 列。假设案例是红色图和控制蓝点。

到目前为止我试过这个:

ggplot(data = d1, aes(x = a1c, y = att, group=status)) +     
 geom_boxplot(colour = d1$status) + geom_jitter(position = position_jitter(
 width = .1, height=0))

我收到此警告:

In addition: Warning messages: 1: Removed 68 rows containing missing values (stat_boxplot). 2: Removed 5 rows containing non-finite values (stat_boxplot).

谢谢,

创建带有边际箱线图的散点图的方法不止一种。我至少知道 2 个:一个带有 ggplotggExtra,另一个带有包 car

您的数据:

d1 <- read.table(header = TRUE, text =
    "a1c   att  status
    8.500000 23.58333  case
    8.450000 12.25000 control
    8.266667 18.91667 control")

ggplot 和 ggExtra

如果您想使用 ggplot,我相信您需要 ggExtra 才能完成这项工作。以下代码可以解决问题

# load the packages
library(ggplot2)
library(ggExtra)

# make a usual ggplot and store it
# point size increased, legend to the bottom
p1 <- ggplot(d1, aes(x=a1c, y=att , color=status)) +
  geom_point(size=2.5) +
  theme(legend.position="bottom")

# marginal boxplot
# relative size of the central plot increased
ggMarginal(p1, type="boxplot", size=7)

生成此图的结果(当然,您可以尝试使用主题等):

备选方案:包车

library(car)
scatterplot(d1$a1c ~ d1$att | d1$status, 
            boxplots = "xy", regLine=FALSE, fill=d1$status, cex=2)

产生下图: