【问题标题】:Having horizontal instead of vertical labels on 2x1 facets and splitting y-label在 2x1 平面上使用水平标签而不是垂直标签并拆分 y 标签
【发布时间】:2014-02-01 16:27:12
【问题描述】:

我想将两个图表合二为一。它们都是时间序列,但尺度不同(比如说身高和体重)。我想展示的方式是让两个图形相互重叠,共享 x-label,但有不同的 y-label。

我有两个不同的问题:

  1. 如果我做 2x1 分面,分面标签的默认位置是在垂直文本的右侧,我宁愿将它们作为(子)标题放在图表顶部
  2. ylab() 为所有方面定义了一个 ylabel,但我有两个不同的变量/尺度。是否可以将其“拆分”并具有两个不同的 ylabel(例如重量为“克”,高度为“英寸”)?

谢谢!

编辑: 好的,这是代码。 mn 是按时间绘制的变量,按风险分组。但mn 的含义取决于var。对于var 的某些值是weight,对于其他值是height

qplot(time, mn, data=d.plot.long,
  color=risk, group=risk,
  geom=c("line","point"),
  position=position_dodge(.2))+
geom_point(size=5, position=position_dodge(.2))+
geom_errorbar(aes(x=time, y=mn, ymin=low, ymax=hi),width=.3 ,position=position_dodge(.2))+
facet_grid(var~.,scales='free_y')+
xlab('Time')+ylab('')+
scale_color_discrete(name="The grouping variable", breaks=c("Hi","Low"), labels=(c("Group A","Group B")))

【问题讨论】:

  • 欢迎来到 StackOverflow。请提出您的问题reproducible by providing sample code and data。这样可以更轻松地发布有用的答案。
  • 看起来你实际上想要两个不同的情节。也许你应该把它分成两个情节并使用grid.arrange安排它们?
  • 正如@Andrie 所说,(示例)数据集也可以更轻松地发布有用的答案。
  • 除此之外,我使用了gridExtra 包的this answer to another question 可能会有所帮助。

标签: r ggplot2


【解决方案1】:

使用gtable:::rbind_gtable;其他答案不会正确对齐轴。

align_plots = function(...){
  pl <- list(...)
  ## test that only passing plots
  stopifnot(do.call(all, lapply(pl, inherits, "gg")))
  gl <- lapply(pl, ggplotGrob)
  bind2 <- function(x,y)
    gtable:::rbind_gtable(x,y,"first") # bug with pmax

  combined <- Reduce(bind2, gl[-1], gl[[1]])

  wl <- lapply(gl, "[[", "widths")
  combined$widths <- do.call(grid::unit.pmax, wl)
  grid::grid.newpage()
  grid::grid.draw(combined)
}

align_plots(qplot(1,1), 
            qplot(100, 100), 
            qplot(1000, 1000) + ylab("two\nlines"))

【讨论】:

    【解决方案2】:

    正如其他人所说,可重复性使问题更容易回答。但是,这是可以通过一般情况轻松回答的问题。

    ggplot2 为单个板上的多个图形提供了一些有限的选项。 R Cookbook 提供了一个非常好且非常易于使用的解决方法here。我可以快速为您介绍您的情况:

    首先,数据框中有两组简单的时间序列:

    year<-c(2010:2014)
    data1<-c(1:5)
    data2<-c(20:24)
    df<-data.frame(year,data1,data2)
    

    接下来,创建图表。由于您希望它们共享 x 轴,我们将从顶部图表中删除它:

    library(ggplot2)
    p1<-qplot(data=df,x=year,y=data1)+theme(axis.title.x = element_blank(), axis.text.x = element_blank())
    p2<-qplot(df,x=year,y=data2)
    

    接下来,运行说明书中的代码来设置多重绘图功能:

    # Multiple plot function ggplot objects can be passed in ..., or to plotlist
    # (as a list of ggplot objects) - cols: Number of columns in layout -
    # layout: A matrix specifying the layout. If present, 'cols' is ignored.  If
    # the layout is something like matrix(c(1,2,3,3), nrow=2, byrow=TRUE), then
    # plot 1 will go in the upper left, 2 will go in the upper right, and 3 will
    # go all the way across the bottom.
    multiplot <- function(..., plotlist = NULL, file, cols = 1, layout = NULL) {
      require(grid)
      # Make a list from the ... arguments and plotlist
      plots <- c(list(...), plotlist)
      numPlots = length(plots)
      # If layout is NULL, then use 'cols' to determine layout
      if (is.null(layout)) {
        # Make the panel ncol: Number of columns of plots nrow: Number of rows
        # needed, calculated from # of cols
        layout <- matrix(seq(1, cols * ceiling(numPlots/cols)), ncol = cols,
                         nrow = ceiling(numPlots/cols))
      }
      if (numPlots == 1) {
        print(plots[[1]])
      } else {
        # Set up the page
        grid.newpage()
        pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
        # Make each plot, in the correct location
        for (i in 1:numPlots) {
          # Get the i,j matrix positions of the regions that contain this subplot
          matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
          print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row, layout.pos.col = matchidx$col))
        }
      }
    }
    

    ...并使用新功能来布置您的图表,一个在另一个之上。

    multiplot(p1,p2,cols=1)
    

    (我想向您展示最终输出,但似乎我没有足够的声誉来发布图片!尝试运行所有这些以亲自查看结果。)

    这就是你要找的吗?

    【讨论】:

      【解决方案3】:

      使用@Joe 的数据,使用gridExtra 包可能更容易。

      代码:

      require(ggplot2)
      require(gridExtra)
      
      p1 <- ggplot(data=df, aes(x=year, y=data1)) + 
        geom_point() +
        theme_bw() +
        theme(
          axis.title.x = element_blank(),
          axis.text.x = element_blank(),
          axis.ticks.x = element_blank()
        )
      
      p2 <- ggplot(data=df, aes(x=year, y=data2)) + 
        geom_point() + 
        theme_bw()
      
      grid.arrange(p1, p2, ncol=1)
      

      结果:

      【讨论】:

        猜你喜欢
        • 2019-08-29
        • 1970-01-01
        • 2020-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-05
        相关资源
        最近更新 更多