首页 文章

使用因子变量来划分R中散点图旁边的直方图

提问于
浏览
2

是否可以使用因子变量来分析R中ggplot2中散点图下方或旁边的直方图(这样直方图是数据的x和y分量)?

我之所以问这是否可以使用因子变量来解决这个问题是因为分面似乎比解决这个问题的可用软件包更通用,例如,可以打开或关闭分面,小平面标签以及分面一种更标准的外观,可能是一个问题 . (默认情况下,分面保留使用相同的轴) .

到目前为止,我还没有能够实现这一点,因为看起来所有分面数据必须具有相同的维数(例如,散点图数据是2D,直方图数据是1D) .

3 回答

  • 1

    我不确定我是否完全理解这个问题,因为因子变量的直方图对我来说没有多大意义 . 此外,没有样本数据,我只需要使用 mtcars . 这样的事情可能会有所帮助 . 除了 ggplot2 之外,我还使用了 grid.extra ,以使图形具有自定义网格排列 .

    library(gridExtra)
    library(ggplot2)
    
    
    s_plot <- ggplot(data = mtcars, aes(x = hp, y = mpg)) + geom_point()
    
    h1 <- ggplot(data = mtcars, aes(x = hp)) + geom_histogram()
    
    h2 <- ggplot(data = mtcars, aes(x = mpg)) + geom_histogram()
    
    grid.arrange(s_plot, h1, h2, layout_matrix = cbind(c(1, 1), c(2, 3)))
    

    enter image description here

    请注意,在 grid.arrangelayout_matrix 参数中,我使用 cbind(c(1,1), c(2, 3)) ,因为我希望第一个绘图本身位于一列中,然后我希望其他两个绘图占据网格第二列中的各个行 .

  • 1

    Consider the use of geom_rug .

    ggplot(mtcars, aes(wt, mpg)) +
      geom_point() + geom_rug()
    

    enter image description here

  • 1

    尼克和布莱恩,

    感谢您对代码的帮助 . 我四处询问,能够得到我想要的设置 . 基本上就是这样,如下所示 . (希望这可能对您和将来的其他人有用,因为我认为这是一种常见的图形类型):

    rm(list = ls())
    library(ggplot2)
    library(gridExtra)
    
    df <- data.frame(
      x = rnorm(100),
      y = rnorm(100)
    )
    
    xrange <- range(pretty(df$x))
    yrange <- range(pretty(df$y))
    
    p.left <- ggplot(df, aes(y)) +
      geom_histogram() +
      lims(x = yrange) +
      coord_flip() +
      theme_light() +
      theme(
        axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        panel.grid.major.x = element_blank(),
        plot.margin = unit(c(1, 0.05, 0.05, 1), "lines")
      )
    
    p.blank <- ggplot() +
      theme_void() +
      theme(plot.margin = unit(rep(0, 4), "lines"))
    
    p.main <- ggplot(df, aes(x, y)) +
      geom_point() +
      lims(x = xrange, y = yrange) +
      theme_light() +
      theme(
        axis.title = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        plot.margin = unit(c(1, 1, 0.05, 0.05), "lines")
      )
    
    p.bottom <- ggplot(df, aes(x)) +
      geom_histogram() +
      lims(x = xrange) +
      theme_light() +
      theme(
        axis.title.y = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank(),
        panel.grid.major.y = element_blank(),
        plot.margin = unit(c(0.05, 1, 1, 0.05), "lines")
      )
    
    lm <- matrix(1:4, nrow = 2)
    
    grid.arrange(
      p.left, p.blank, p.main, p.bottom,
      layout_matrix = lm,
      widths = c(1, 5),
      heights = c(5, 1),
      padding = unit(0.1, "line")
    )
    

    Scatterplot with histograms of x- and y-components of the data.

相关问题