当一些图例有传说而另一些没有传说时,将ggplot2中的多个图对齐 [英] Align multiple plots in ggplot2 when some have legends and others don't

查看:156
本文介绍了当一些图例有传说而另一些没有传说时,将ggplot2中的多个图对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了



我想要的是让x轴对齐,缺少的图例由空白区域填充。这是可能的吗?



编辑:

一个由桑迪Muspratt下面。



我实现它,它用两张图很好地工作。

然后我

 图书馆(ggplot2)
图书馆(reshape2)
library(gridExtra)

x = seq(0,10,length.out = 200)
y1 = sin(x)
y2 = cos x)
y3 = sin(x)* cos(x)
y4 = sin(2 * x)* cos(2 * x)

df1 < - 数据。 frame(x,y1,y2)
df1 < - melt(df1,id.vars =x)

g1 < - ggplot(df1,aes(x,value, color = variable))+ geom_line()
g1 < - g1 + theme_bw()
g1 < - g1 + theme(legend.key = element_blank())
g1 < - < g1 + ggtitle(图1,小标题=带图例)

df2 < - data.frame(x,y3)
g2 < - ggplot(df2,aes x),y))+ geom_line()
g2 < - g2 + theme_bw()
g2 < - g2 + theme(legend.key = element_blank())
g2 < - g2 + ggtitle(图2,subtitle =Without legend)

df3 < - data。 frame(x,y3,y4)
df3 < - melt(df3,id.vars =x)

g3 < - ggplot(df3,aes(x,value, color = variable))+ geom_line()
g3 < - g3 + theme_bw()
g3 < - g3 + theme(legend.key = element_blank())
g3 < - g3 + scale_color_discrete(这实际上是一个很长的标题)
g3 < - g3 + ggtitle(图3,字幕=带图例)

gA < - ggplotGrob(g1)
gB <-ggplotGrob(g2)
gC <-ggplotGrob(g3)

gB = gtable :: gtable_add_cols(gB,sum(gC $ widths [7:8]),6)

maxWidth <-grid :: unit.pmax(gA $ widths [2:5],gB $ widths [2:5],gC $ widths [ 2:5])
gA $ widths [2:5]< - maxWidth
gB $ widths [2:5]< - maxWidth
gC $ widths [2:5]< ; - maxWidth

g< - arrangeGrob(gA,gB,gC,ncol = 1)
grid :: grid.newpage()
grid :: grid.draw(g )

这个结果在下图中:



我在这里和其他关于这个主题的问题中找到答案的主要问题是人们在矢量 myGrob $ widths 中玩了很多,而没有真正解释他们为什么要这样做。我看到有人修改 myGrob $ widths [2:5] others myGrob $ widths [2:3] 和I只是找不到任何文档解释这些列是什么。



我的目标是创建一个通用的函数,如:

  AlignPlots<  -  function(...){
#检索图表列表以对齐
plots.list< - list(.. 。)

#初始化列表
grobs.list< - list()
widths.list< - list()

#收集(i中的1:长度(plots.list)){b的每个grob的宽度
max.nb.grobs < - 0
longest.grob< - NULL
{
if(i!= length(plots.list)){
plots.list [[i]]< - plots.list [[i]] + theme(axis.title.x = element_blank ())
}

grobs.list [[i]]< - ggplotGrob(plots.list [[i]])
current.grob.length< - 长度(grobs.list [[i]])
if(current.grob.length> max.nb.grobs){
max.nb.grobs< - current。 grob.length
longest.grob< - grobs.list [[i]]
}

widths.list [[i]]< - grobs.list [[ i]] $ widths [2:5]
}

#获取最大宽度
maxWidth< - do.call(grid :: unit.pmax,widths.list )

#为每个grob
分配最大宽度(我在1:length(grobs.list)){
if(length(grobs.list [[i] ]) (gbbs.b.grobs){
grobs.list [[i]]< - gtable :: gtable_add_cols(grobs.list [[i]],
sum(longest.grob $ widths [7: 8]),
6)
}
grobs.list [[i]] $ widths [2:5]< - as.list(maxWidth)
}

#生成绘图
g< - do.call(arrangeGrob,c(grobs.list,ncol = 1))

return(g)
}


解决方案

感谢 ,发表评论(然后删除),我想出了以下一般解决方案。



我喜欢Sandy Muspratt的回答,蛋包似乎以非常优雅的方式完成工作,但由于它是实验性的和脆弱的,我更喜欢使用这种方法:

 #'垂直对齐图表列表。 
#'
#'此函数对齐给定的图表列表,使x轴对齐。
#'它假定这些图共享x个数据的相同范围。
#'
#'@param ...要对齐的图表列表。
#'@param globalTitle分配给新创建图形的标题。
#'@param keepTitles如果您想保留每个单独的
#'图的标题,则为TRUE。
#'@param keepXAxisLegends如果您想保留每个
#个别图的x轴标签,则为TRUE。否则,它们全部被移除,除了底部的图
#'之外。
#'@param nb.columns生成图形的列数。
#'
#'@return包含对齐图的gtable。
#'@examples
#'g <-VAlignPlots(g1,g2,g3,globalTitle =对齐测试)
#'grid :: grid.newpage()
#'grid :: grid.draw(g)
VAlignPlots< - function(...,
globalTitle =,
keepTitles = FALSE,
keepXAxisLegends = FALSE ,
nb.columns = 1){
#检索图表列表以对齐
plots.list< - list(...)

#删除如果请求单个图标题
if(!keepTitles){
plots.list< - lapply(plots.list,function(x)x< -x + ggtitle())
plots.list [[1]]< - plots.list [[1]] + ggtitle(globalTitle)
}

#删除所有图上的x轴标签,除最后一个,如果请求
if(!keepXAxisLegends){
plots.list [1:(length(plots.list)-1)]< -
lapply(plots.list [ 1:(length(plots.list)-1)],
function(x)x < - x + theme(axis.titl ex = element_blank()))
}

#构建grobs列表
grobs.list< - lapply(plots.list,ggplotGrob)

#获取最大宽度
widths.list< - do.call(grid :: unit.pmax,lapply(grobs.list,[[,'widths'))

#将最大宽度分配给所有grobs
grobs.list< - lapply(grobs.list,function(x){
x [['widths']] = widths.list
x} )

#创建gtable并显示它
g< - grid.arrange(grobs = grobs.list,ncol = nb.columns)
#另一种方法是使用arrangeGrob这将创建没有
#的表格
#g< - do.call(arrangeGrob,c(grobs.list,ncol = nb.columns))

return (g)
}


I have used the method indicated here to align graphs sharing the same abscissa.

But I can't make it work when some of my graphs have a legend and others don't.

Here is an example:

library(ggplot2)
library(reshape2)
library(gridExtra)

x = seq(0, 10, length.out = 200)
y1 = sin(x)
y2 = cos(x)
y3 = sin(x) * cos(x)

df1 <- data.frame(x, y1, y2)
df1 <- melt(df1, id.vars = "x")

g1 <- ggplot(df1, aes(x, value, color = variable)) + geom_line()
print(g1)

df2 <- data.frame(x, y3)
g2 <- ggplot(df2, aes(x, y3)) + geom_line()
print(g2)

gA <- ggplotGrob(g1)
gB <- ggplotGrob(g2)
maxWidth <- grid::unit.pmax(gA$widths[2:3], gB$widths[2:3])
gA$widths[2:3] <- maxWidth
gB$widths[2:3] <- maxWidth
g <- arrangeGrob(gA, gB, ncol = 1)
grid::grid.newpage()
grid::grid.draw(g)

Using this code, I have the following result:

What I would like is to have the x axis aligned and the missing legend being filled by a blank space. Is this possible?

Edit:

The most elegant solution proposed is the one by Sandy Muspratt below.

I implemented it and it works quite well with two graphs.

Then I tried with three, having different legend sizes, and it doesn't work anymore:

library(ggplot2)
library(reshape2)
library(gridExtra)

x = seq(0, 10, length.out = 200)
y1 = sin(x)
y2 = cos(x)
y3 = sin(x) * cos(x)
y4 = sin(2*x) * cos(2*x)

df1 <- data.frame(x, y1, y2)
df1 <- melt(df1, id.vars = "x")

g1 <- ggplot(df1, aes(x, value, color = variable)) + geom_line()
g1 <- g1 + theme_bw()
g1 <- g1 + theme(legend.key = element_blank())
g1 <- g1 + ggtitle("Graph 1", subtitle = "With legend")

df2 <- data.frame(x, y3)
g2 <- ggplot(df2, aes(x, y3)) + geom_line()
g2 <- g2 + theme_bw()
g2 <- g2 + theme(legend.key = element_blank())
g2 <- g2 + ggtitle("Graph 2", subtitle = "Without legend")

df3 <- data.frame(x, y3, y4)
df3 <- melt(df3, id.vars = "x")

g3 <- ggplot(df3, aes(x, value, color = variable)) + geom_line()
g3 <- g3 + theme_bw()
g3 <- g3 + theme(legend.key = element_blank())
g3 <- g3 + scale_color_discrete("This is indeed a very long title")
g3 <- g3 + ggtitle("Graph 3", subtitle = "With legend")

gA <- ggplotGrob(g1)
gB <- ggplotGrob(g2)
gC <- ggplotGrob(g3)

gB = gtable::gtable_add_cols(gB, sum(gC$widths[7:8]), 6)

maxWidth <- grid::unit.pmax(gA$widths[2:5], gB$widths[2:5], gC$widths[2:5])
gA$widths[2:5] <- maxWidth
gB$widths[2:5] <- maxWidth
gC$widths[2:5] <- maxWidth

g <- arrangeGrob(gA, gB, gC, ncol = 1)
grid::grid.newpage()
grid::grid.draw(g)

This results in the following figure:

My main problem with the answers found here and in other questions regarding the subject is that people "play" quite a lot with the vector myGrob$widths without actually explaining why they are doing it. I have seen people modify myGrob$widths[2:5] others myGrob$widths[2:3] and I just can't find any documentation explaining what those columns are.

My objective is to create a generic function such as:

AlignPlots <- function(...) {
  # Retrieve the list of plots to align
  plots.list <- list(...)

  # Initialize the lists
  grobs.list <- list()
  widths.list <- list()

  # Collect the widths for each grob of each plot
  max.nb.grobs <- 0
  longest.grob <- NULL
  for (i in 1:length(plots.list)){
    if (i != length(plots.list)) {
      plots.list[[i]] <- plots.list[[i]] + theme(axis.title.x = element_blank())
    }

    grobs.list[[i]] <- ggplotGrob(plots.list[[i]])
    current.grob.length <- length(grobs.list[[i]])
    if (current.grob.length > max.nb.grobs) {
      max.nb.grobs <- current.grob.length
      longest.grob <- grobs.list[[i]]
    }

    widths.list[[i]] <- grobs.list[[i]]$widths[2:5]
  }

  # Get the max width
  maxWidth <- do.call(grid::unit.pmax, widths.list)

  # Assign the max width to each grob
  for (i in 1:length(grobs.list)){
    if(length(grobs.list[[i]]) < max.nb.grobs) {
      grobs.list[[i]] <- gtable::gtable_add_cols(grobs.list[[i]],
                                                 sum(longest.grob$widths[7:8]),
                                                 6)
    }
    grobs.list[[i]]$widths[2:5] <- as.list(maxWidth)
  }

  # Generate the plot
  g <- do.call(arrangeGrob, c(grobs.list, ncol = 1))

  return(g)
}

解决方案

Thanks to this and that, posted in the comments (and then removed), I came up with the following general solution.

I like the answer from Sandy Muspratt and the egg package seems to do the job in a very elegant manner, but as it is "experimental and fragile", I preferred using this method:

#' Vertically align a list of plots.
#' 
#' This function aligns the given list of plots so that the x axis are aligned.
#' It assumes that the graphs share the same range of x data.
#'
#' @param ... The list of plots to align.
#' @param globalTitle The title to assign to the newly created graph.
#' @param keepTitles TRUE if you want to keep the titles of each individual
#' plot.
#' @param keepXAxisLegends TRUE if you want to keep the x axis labels of each
#' individual plot. Otherwise, they are all removed except the one of the graph
#' at the bottom.
#' @param nb.columns The number of columns of the generated graph.
#'
#' @return The gtable containing the aligned plots.
#' @examples
#' g <- VAlignPlots(g1, g2, g3, globalTitle = "Alignment test")
#' grid::grid.newpage()
#' grid::grid.draw(g)
VAlignPlots <- function(...,
                       globalTitle = "",
                       keepTitles = FALSE,
                       keepXAxisLegends = FALSE,
                       nb.columns = 1) {
  # Retrieve the list of plots to align
  plots.list <- list(...)

  # Remove the individual graph titles if requested
  if (!keepTitles) {
    plots.list <- lapply(plots.list, function(x) x <- x + ggtitle(""))
    plots.list[[1]] <- plots.list[[1]] + ggtitle(globalTitle)
  }

  # Remove the x axis labels on all graphs, except the last one, if requested
  if (!keepXAxisLegends) {
    plots.list[1:(length(plots.list)-1)] <-
      lapply(plots.list[1:(length(plots.list)-1)],
             function(x) x <- x + theme(axis.title.x = element_blank()))
  }

  # Builds the grobs list
  grobs.list <- lapply(plots.list, ggplotGrob)

  # Get the max width
  widths.list <- do.call(grid::unit.pmax, lapply(grobs.list, "[[", 'widths'))

  # Assign the max width to all grobs
  grobs.list <- lapply(grobs.list, function(x) {
    x[['widths']] = widths.list
    x})

  # Create the gtable and display it
  g <- grid.arrange(grobs = grobs.list, ncol = nb.columns)
  # An alternative is to use arrangeGrob that will create the table without
  # displaying it
  #g <- do.call(arrangeGrob, c(grobs.list, ncol = nb.columns))

  return(g)
}

这篇关于当一些图例有传说而另一些没有传说时,将ggplot2中的多个图对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆