首页 > 解决方案 > 如何使用虹膜数据绘制这个?

问题描述

使用鸢尾花数据集

我想绘制如下图:使用viewport(),散点图的宽度和高度都是0.66

我有两个问题:

1.) 正如您在第二个图(右侧)中看到的那样,图有更平滑的线条,但在第一个图(右侧)中,我们仍然可以看到线条。如何以第一个和第二个情节看起来完全相同的方式进行绘图?

2.) 如何使用 viewport()、pushViewport() 和 upViewport() 等网格视口树绘制相同的图)

这是我的示例代码:

library(ggplot2)
library(readr)
library(grid)
library(gridBase)

 head(x = iris)

  a <- ggplot(data = iris,
   aes(x=Sepal.Length, y=Sepal.Width)) + 
    geom_point()



  b <- ggplot(data = iris,
   aes(x = Sepal.Length)) + 
    geom_histogram()


  c <- ggplot(data = iris,
      aes(x = Sepal.Width)) + 
      geom_histogram() +
      coord_flip()


   # Put these graphs into one

      grid.newpage()
      pushViewport(viewport(layout = grid.layout(2, 2)))
      vplayout <- function(x, y) viewport(layout.pos.row = x, 
                                layout.pos.col = y)
      print(b, vp = vplayout(1, 1))  # key is to define vplayout
      print(a, vp = vplayout(2, 1)) 
      print(c, vp = vplayout(2, 2))

      sample_vp <- viewport(width = 0.66, height = 0.66)

      pushViewport(sample_vp)

先感谢您

我的输出:

在此处输入图像描述

预期输出:

在此处输入图像描述

标签: rggplot2griddataset

解决方案


对于 1),是的,这些线条很难看。我不知道是什么导致了它们,但由于每个条都是一个矩形,我认为它一定是图形故障。您可能可以通过将直方图颜色设置为与填充相同来防止这种情况。

对于 2),我将玩冒险游戏,不给出你想听到的答案(即如何在网格中进行这些操作),而是给你一个我认为你需要听到的答案。

假设您的目标是将这些直方图作为边缘直方图显示到主面板,您可以轻松地拼凑起来实现类似的效果。

library(ggplot2)
library(patchwork)
#> Warning: package 'patchwork' was built under R version 3.6.3

a <- ggplot(data = iris,
            aes(x=Sepal.Length, y=Sepal.Width)) + 
  geom_point()

b <- ggplot(data = iris,
            aes(x = Sepal.Length)) + 
  geom_histogram()


c <- ggplot(data = iris,
            aes(x = Sepal.Width)) + 
  geom_histogram() +
  coord_flip()

b + plot_spacer() + a + c + 
  plot_layout(nrow = 2, ncol = 2, widths = c(1, 0.5), heights = c(0.5, 1))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

reprex 包(v0.3.0)于 2020-04-18 创建

您还可以通过设置中断和名称来保留边缘图的轴:

b + scale_x_continuous(breaks = NULL, name = "") + 
  plot_spacer() +
  a + 
  c + scale_x_continuous(breaks = NULL, name = "") +
  plot_layout(nrow = 2, ncol = 2, widths = c(1, 0.5), heights = c(0.5, 1))


推荐阅读