ggplot做分组柱形图时,已修正errorbar堆积问题,但errorbar仍无法与col对齐:
g<-ggplot(cgm1,aes(x=sample,y=mean,fill=surdig))+
geom_bar(stat = 'identity',position = position_dodge2(width=0.5))+
theme(panel.grid.major = element_blank(),
panel.grid.minor=element_blank(),
panel.background = element_blank(),
axis.line=element_line(colour="black",size=0.6))+
xlab(NULL)+ylab("Interstitial glucose level,mmol/L")+
theme(legend.title = element_blank(),legend.key.height = unit(.5,'cm'),
legend.key.width = unit(.5,'cm'),
legend.position = 'top',
legend.box.just = 'top')
g1<-g+geom_errorbar(aes(ymin=mean-se,ymax=mean+se),width=0.2,
position = position_dodge2(width=0.5))
g1
输出是这样的
在分组柱形图中,如果希望errorbar与柱形图的颜色对齐,可以将aes()函数中的fill参数设置为与geom_bar()中的fill参数一致,并将position参数设置为position_dodge2()函数中的preserve = "single",以确保errorbar在柱形图中间对齐。
下面是修改后的代码:
g <- ggplot(cgm1, aes(x = sample, y = mean, fill = surdig)) +
geom_bar(stat = 'identity', position = position_dodge2(width = 0.5)) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black", size = 0.6)) +
xlab(NULL) + ylab("Interstitial glucose level,mmol/L") +
theme(legend.title = element_blank(), legend.key.height = unit(0.5, 'cm'),
legend.key.width = unit(0.5, 'cm'),
legend.position = 'top',
legend.box.just = 'top')
g1 <- g + geom_errorbar(aes(ymin = mean - se, ymax = mean + se, fill = surdig), width = 0.2,
position = position_dodge2(width = 0.5, preserve = "single"))