简体   繁体   中英

Mean and median boxplot legend in the ggplot2 function

I'm trying to add a caption identifying that the "ball" is the average and the "line" is the median of the boxplot chart as follows:

mediasCon1 = tapply(dados$FS, dados$Trat, mean)

boxplot(dados$FS ~ dados$Trat, data = dados, col="gray", 
        xlab = 'Tratamentos', ylab = 'Espermatozoides - Cauda Solta')
points(1:3, mediasCon1, col = 'black', pch = 16)
legend("topleft", legend=c("Média", "Mediana"),
       lty=c(NA,1), col="black", lwd=1:3, bty="n", pch=c(16,NA))

However, when using the ggplot2 function the following error appears:

ggplot(data=dados, aes(x=Trat, y=FS)) + geom_boxplot(fill=c("#DEEBF7","#2171B5","#034E7B"),color="black") +
  xlab('Tratamentos') +
  ylab('Espermatozoides - Cauda Solta') + 
  stat_summary(fun=mean, colour="black", geom="point", 
               shape=18, size=5) + 
  theme(axis.title = element_text(size = 20),
        axis.text = element_text(size = 16)) +
legend("topleft", legend=c("Média", "Mediana"),
       lty=c(NA,1), col="black", lwd=1:3, bty="n", pch=c(16,NA))

Error in strwidth(legend, units = "user", cex = cex, font = text.font) : 
  plot.new has not been called yet

Try this approach:

library(ggplot2)
#Code
ggplot(data=dados, aes(x=Trat, y=FS)) + 
  geom_line(aes(linetype='median'),size=1)+
  geom_point(aes(shape='mean'),size=5)+
  geom_boxplot(fill=c("#DEEBF7","#2171B5","#034E7B"),color="black") +
  xlab('Tratamentos') +
  ylab('Espermatozoides - Cauda Solta') + 
  stat_summary(fun=mean, colour="black", geom="point", 
               shape=18, size=5) + 
  theme(axis.title = element_text(size = 20),
        axis.text = element_text(size = 16))+
  scale_linetype_manual('Variable',values='solid')+
  scale_shape_manual('',values = 18)+
  theme(legend.spacing.y = unit(0.1, "cm"))

Output:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM