我有一个数据集,其中有两组分别进行了测试和重新测试。我创建了一个图,显示四个箱形图(组x测试),每个测量点。每个受试者的测试和重新测试分数用一条线连接,并且根据测试或重新测试会话对箱线图进行着色。
现在,我想根据组填充或取消填充箱形图。我通过在下面的代码中切换geom_boxplot选项,然后将它们合并到photoshop中来创建两个图(填充图和未填充图),从而创建了下图。但是,我想知道是否有办法用ggplot完全创建这个图?
library(ggplot2)
group <- c("HC","HC","HC","HC","HC","HC","HC","HC","HC","HC","HC","HC","HC","HC","PAT","PAT","PAT","PAT","PAT","PAT","PAT","PAT","PAT","PAT")
session <- c("test","retest","test","retest","test","retest","test","retest","test","retest","test","retest","test","retest","test","retest","test","retest","test","retest","test","retest","test","retest")
value <- c(2,1.998521753,1.874733659,1.718486493,1.623289857,1.546827187,1.423472302,1.391178972,1.706069109,1.633178623,1.55107172,1.529644866,1.85152853,1.955804538,1.642797713,1.618263891,1.332975483,1.191228234,1.314644375,1.18511437,1.881207152,1.764699552,1,1.001585308)
index <- c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12)
df <- data.frame(group, session, value, index, U = interaction(session,group))
p <- ggplot(df, aes(x=U, y=value))
p <- p + geom_boxplot(aes(fill=session), data=df, colour="black", outlier.alpha=0.0, lwd=0.8, alpha=0.94)
# p <- p + geom_boxplot(aes(colour=session), data=df, outlier.alpha=0.0, lwd=0.8)
dat <- ggplot_build(p)$data[[1]]
p <- p + geom_segment(data=dat, aes(x=xmin, xend=xmax, y=middle, yend=middle), colour="grey70", size=1.6)
p <- p + stat_summary(fun.y=mean,geom="point",pch="-",colour="grey30",size=8, position = position_dodge(width=0.75))
p <- p + geom_line(aes(group = index), alpha = 0.7, colour ="grey50", data=df)
p <- p + geom_point(size=2, aes(group=session), colour="black", data=df, position = position_dodge(width=0.75))
p <- p + scale_x_discrete(labels=c("HC-test","HC-retest","PAT-test","PAT-retest"))
p <- p + scale_y_continuous(limits=c(0.9,2.1), breaks=c(1,1.5,2))
p <- p + scale_colour_manual(values=c("#bf812d","#35978f"))
p <- p + scale_fill_manual(values=c("#bf812d","#35978f"))
p <- p + theme_bw()
p <- p + theme(
axis.text.x = element_text(colour = "black"),
axis.text.y = element_text(colour = "black"),
axis.title.x = element_blank(),
axis.title.y = element_text(colour = "black"),
legend.position = "none",
panel.border = element_rect(colour = "black", fill=NA, size=1)
)
p <- p + labs(y=expression("Normalized Volume(mm)"^3))
ggsave("~/Desktop/test.pdf", width=5, height=4, units=c("in"), plot=p)
答案 0 :(得分:2)
您可以尝试不同地设置因子顺序。您还需要在values
中指定足够数量的scale_xxx_manual
。我将示例简化为仅包含方框,因为这是您的重点问题。
df$session <- factor(df$session, levels = c("test", "retest"))
df$U = interaction(df$group, df$session, lex.order = TRUE)
ggplot(df, aes(x = U, y = value, fill = U, color = U)) +
geom_boxplot() +
scale_fill_manual(values = c("white", "white", "#bf812d", "#35978f"), guide = "none") +
scale_color_manual(values = c("#bf812d", "#35978f", "black", "black"), guide = "none")