使用虹膜数据集
我想绘制如下图:使用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)
提前谢谢您
我的输出:
预期输出:
对于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 package(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))
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLmltZ3VyLmNvbS9IbVFOTHo1LnBuZyJ9” alt =“”>