简体   繁体   中英

How to address the issue in plot size and legend in ggplot?

I need help in ggplot and a sharing legend. Below is the Minimum working example which is similar to the problem I am struggling with. I need to adjust the sizes of these plots similar excluding the "ytick labels" on first plot. Also, the legend should come under the center of all three plots. I would appreciate any help in this.![enter image description here][1]...

The code I am using is given below..

 require(ggplot2) require(grid) require(gtable) require(gridExtra) Sp <- c("A","B","C","E","G","F","D","H","I") Cl <- c("One","Two","Three","One","Two","Three","One","Two","Three") S1 <- c(0,1,1,0,3,1,3,2,3) S2 <- c(2,0,3,2,0,2,2,0,1) S3 <- c(0,3,0,1,1,0,1,3,1) data <- as.data.frame(cbind(Sp,Cl,S1,S2,S3)) data$Sp <- as.character(data$Sp) data$Sp <- factor(data$Sp, levels=unique(data$Sp)) p1 <- ggplot(data=data, aes(x=Sp, y=S1, fill=Cl)) + geom_bar(stat="identity") + coord_flip() + theme_bw() + theme(axis.title.y = element_blank()) + theme(legend.position="bottom") + theme(plot.margin = unit(c(0.5, 0.25, 0.5, 0.25), "cm")) p2 <- ggplot(data=data, aes(x=Sp, y=S2, fill=Cl)) + geom_bar(stat="identity") + coord_flip() + theme_bw() + theme(axis.title.y=element_blank(), axis.text.y=element_blank()) + theme(plot.margin = unit(c(0.5, 0.25, 0.5, 0.25), "cm")) p3 <- ggplot(data=data, aes(x=Sp, y=S3, fill=Cl)) + geom_bar(stat="identity") + coord_flip() + theme_bw() + theme(axis.title.y=element_blank(), axis.text.y=element_blank()) + theme(plot.margin = unit(c(0.5, 0.25, 0.5, 0.25), "cm")) ## Single legend g_legend <- function(a.gplot){ tmp <- ggplot_gtable(ggplot_build(a.gplot)) leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box") legend <- tmp$grobs[[leg]] return(legend)} ######################################### mylegend <- g_legend(p1) ######################################### p4 <- grid.arrange(p1 + theme(legend.position="none"), arrangeGrob(p2 + theme(legend.position="none"), p3 + theme(legend.position="none"), nrow=1), widths=c(1, 1, 1), nrow=2, mylegend, heights=c(10,0.5)) 

It's better to change the data frame using tidyr package. I used facet_grid function instead of combining many plots.

library(ggplot2)
require(grid)
require(gtable)
library(gridExtra)
Sp <- c("A","B","C","E","G","F","D","H","I")
Cl <- c("One","Two","Three","One","Two","Three","One","Two","Three")
S1 <- c(0,1,1,0,3,1,3,2,3)
S2 <- c(2,0,3,2,0,2,2,0,1)
S3 <- c(0,3,0,1,1,0,1,3,1)

data <- as.data.frame(cbind(Sp,Cl,S1,S2,S3))

library(tidyr)
datanew<- gather(data, key, value, S1:S3)
datanew
ggplot(datanew, aes(x=Sp, y=value, fill=Cl))+geom_bar(stat="identity")+coord_flip() +
        theme_bw() +facet_grid(~key)+
        theme(legend.position="bottom")

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