【问题标题】:How to address the issue in plot size and legend in ggplot?如何解决 ggplot 中的绘图大小和图例问题?
【发布时间】:2015-03-12 02:09:53
【问题描述】:

我需要 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))

【问题讨论】:

    标签: r plot ggplot2 alignment legend


    【解决方案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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多