Reputation: 307
Using Iris dataset
I would to like to plot as shown: using viewport(), and both the width and height of the scatter plot are 0.66
I have two issues:
1.) As you see in second plot (right side) plot has more smooth lines but in first plot (right side) we can still see the lines. How to plot in such a way that 1st and 2nd plot looks exactly same way?
2.) How can I plot same plot using tree of grid viewport like viewport(), pushViewport(), and upViewport())
Here's my sample code:
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)
Thank you in advance
My output:
Expected Output:
Upvotes: 1
Views: 460
Reputation: 38063
For 1), yes these lines are ugly. I don't know what is causing them, but since every bar is a rectangles I think it must be a graphical glitch. You probably could prevent this by setting the histogram colour identical to the fill.
For 2), I'm going to play the risky game of not giving the answer that you want to hear (namely how to do these operations in grid), but giving you an answer I think you need to hear.
Assuming your goal is to display these histograms as marginal histograms to the main panel, you can easily achieve something like this in patchwork.
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`.
Created on 2020-04-18 by the reprex package (v0.3.0)
You could also leave the axes of the marginal plots out by setting breaks and names:
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))
Upvotes: 3