如何解决ggplot中的绘图大小和图例中的问题?

时间:2015-03-12 02:09:53

标签: r plot ggplot2 alignment legend

我需要ggplot和共享传奇方面的帮助。下面是最小工作示例,类似于我正在努力解决的问题。我需要调整这些图的大小,不包括第一个图上的“ytick标签”。此外,图例应该位于所有三个图的中心。我将不胜感激任何帮助。![在此输入图像描述] [1] ...

我正在使用的代码如下:

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))

1 个答案:

答案 0 :(得分:1)

最好使用tidyr包更改数据框。我使用了facet_grid函数,而不是组合了许多图。

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")