I am using ggpairs
from the GGally
package to make a scatterplot matrix by setting upper = list(continuous = "points")
.
I realized that the density plot along the diagonal actually takes over the y-axis limit for the first row of plots. In other words, the y-axis ticks for that first row are actually wrong. They should be 9-11 instead of 0-0.6.
How can I get valid ticks? I tried to set the diagonals to "blank"
, but this erases the ticks altogether. I also tried to specify a custom function, but I can’t figure out the syntax.
library(tidyverse)
library(GGally)
#> Registered S3 method overwritten by 'GGally':
#> method from
#> +.gg ggplot2
rn <- partial(runif, min = -1, max = 1)
tibble(ten = 10 + rn(100), twenty = 20 + rn(100), thirty = 30 + rn(100)) |>
ggpairs(
upper = list(continuous = "points"),
#diag = list(continuous = function(data, mapping) {ggplot(data) + aes(x, y) + geom_point()}))
#diag = list(continuous = function(data, mapping) {ggplot(data) + mapping + geom_point()}))
)
Created on 2024-07-16 with reprex v2.1.0
I don’t see an (easy) option to achieve your desired result using ggpairs
. But one option would be to build your pairsplot from scratch using ggmatrix
which allows for more fine-control over the scales and axes.
Basically I use layer_scales
to get the limits of the scales for the density plots, then do some rescaling to get the x axis breaks and labels for the y axis too.
library(tidyverse)
library(GGally)
set.seed(123)
rn <- partial(runif, min = -1, max = 1)
dat <- tibble(ten = 10 + rn(100), twenty = 20 + rn(100), thirty = 30 + rn(100))
p_list <- expand.grid(
x = names(dat), y = names(dat),
stringsAsFactors = FALSE
) |>
purrr::pmap(
(x, y) {
geom_layer <- if (x == y) {
geom_density(aes(.data[[x]]))
} else {
geom_point(aes(.data[[x]], .data[[y]]))
}
p <- ggplot(dat) +
geom_layer
if (x == y) {
from <- layer_scales(p)$y$get_limits()
to <- layer_scales(p)$x$get_limits()
p <- p +
scale_y_continuous(
breaks = scales::rescale(
scales::breaks_extended()(to),
from = to,
to = from
),
labels = (x) {
scales::rescale(
x,
from = from,
to = to
)
}
)
}
p
}
)
ggmatrix(
p_list, nrow = 3, ncol = 3,
xAxisLabels = names(dat),
yAxisLabels = names(dat)
)