我正在尝试用ggplot
制作grouped boxplots
。我的代码生成了分组的箱线图。但是,有很多东西我想在箱线图上改进:
1)删除scale_fill_manual
引入的第二个图例
2)保留代码中的颜色,更改箱线图,使其看起来像以下设计:
用我的代码生成的箱线图确实具有上述透明度,但是须状线穿过了箱形图(看起来不太好)。median
应该像上面的示例一样可见,并且须状线不应该穿过箱形图。
以下是我到目前为止所尝试的。双重图例是一个问题,胡须穿过箱线图是另一个问题。
样本数据和代码:
library(ggplot2)
## create some data.frames: this results in a list of four dfs
createDF <- quote(data.frame(id=sample(c("NN", "SS","H"), 100, rep=T),
heavy=runif(100),
heavier=runif(100),
heaviest=runif(100)))
dfs <- lapply(1:4, function(i) eval(createDF))
## join and shape them
library(reshape2)
dat <- do.call(rbind, dfs)
dat$dfid <- paste("df", rep(1:4, times=sapply(dfs, nrow)))
dat <- melt(dat, id.vars=c("id", "dfid"))
#-----plot
ggplot(dat, aes(x = factor(id, level = c('H', 'NN', 'NS')), y=value, group=interaction(variable, id), fill=variable, colour=variable)) +
stat_boxplot(geom ='errorbar', width = 0.6,lwd = 0.9,position = position_dodge2(preserve = "single"))+
geom_boxplot(aes(fill=variable, colour=variable),width = 0.6,lwd = 0.9,outlier.shape = NA,outlier.colour = NULL, coef = 0,
position = position_dodge2(preserve = "single"),alpha = 0.6,fatten = 2) +
coord_cartesian(ylim = c(0, 1))+
scale_y_continuous(limits = c(0, 1), breaks = seq(0, 1, by = .25),expand = c(0, 0)) +
facet_grid(.~dfid)+ #reorder facets
scale_fill_manual(values=c("#4daf4a","#984ea3","#ffff99","#ff7f00","#e41a1c"),name="")+ # scale_fill_manual(values = c('1' = "black", '2' = "white", '3' = "darkred", '4' = "lightblue"))
scale_color_manual(name = "scenario", values = c("#4daf4a","#984ea3","#ffff99","#ff7f00","#e41a1c"))+
labs(y = "Values", x = "")+
theme_bw()+
theme(strip.text.x = element_text(size = 14, colour = "black", angle = 0, face = "bold"),
axis.text = element_text(size = 12, color = "black"),
text = element_text(size = 18),
axis.text.x = element_text(angle = 0, hjust = 0.5, size = 9, colour = "black", face = "bold"),
legend.direction = "vertical",
legend.position = "right",
panel.background = element_rect(fill = "grey70"),
panel.border = element_rect(colour = "black", fill=NA, size=1))+
theme(legend.direction ="vertical",legend.position = c(0.5, .79))+
guides(fill=guide_legend(nrow=1))+ theme(legend.title = element_blank())+theme(legend.text = element_text(colour="black", size = 10, face = "bold"))+
theme(legend.margin=margin(-10, 0, 0, 0))+
theme(panel.grid.major = element_line(colour="white", size = 0.2),
panel.grid.minor = element_blank())
#theme(plot.margin = unit(c(0,0.0,0,0.2), "lines"))
1条答案
按热度按时间ukxgm1gy1#
这个设计怎么样:第一个问题很简单:要删除第二个图例,只需在
scale_fill_manual
和scale_color_manual
中添加guide = "none"
。第二个问题是通过使用
position_dodge(1)
定位箱形图实现的,颜色设计可能是一种解决方案: