Problem
I am trying to understand how to provide y-axis breaks manually to facets, generated by the facet_wrap()
function in ggplot2
in R
.
Minimal reproducible example
Disclaimer: I have borrowed the following example from the R studio community
With the following code, you can specify the y-axis breaks based on the y-axis values in de dataset.
library(ggplot2)
diamonds2 <- subset(diamonds, !(cut == "Fair" & price > 5000))
my_breaks <- function(x) { if (max(x) < 6000) seq(0, 5000, 1000) else seq(0, 15000, 5000) }
ggplot(data = diamonds2, aes(x = carat, y = price)) +
facet_wrap(~ cut, scales = "free_y") +
geom_point() +
scale_y_continuous(breaks = my_breaks)
Question
I would like to be able to specify the breaks manually, based on the facet
(in this case: based on the 'cut' of the diamonds). For example, I would like to set the breaks for the 'Fair' cut to seq(1000, 2500, 5000)
, the breaks for the 'Good' cut to seq(1500, 3000, 4500, 6000, ..., 15000)
and the rest to seq(0,15000, 5000)
.
Attempt
I thought that adapting the my_breaks
function with an if-else-ladder, specifying the 'cut' would solve the problem, however, it doesn't:
my_breaks <- function(x) {
if (cut == "Fair") {seq(0, 5000, 1000) }
else if (cut == "Good") {seq(1500,15000, 1500)}
else { seq(0, 15000, 5000) }
}
It provides the error:
Error in cut == "Fair" : comparison (1) is possible only for atomic and list types
Is there another approach to manually provide the breaks to different facets?
cut
refers to a function in base r (rdocumentation.org/packages/base/versions/3.6.2/topics/cut). Even, if you pass cut somehow as argument to the function, I'm not sure, whether it would work properly. Wouldn'tfacet_wrap(~ cut, scales = "free") +
(i.e. also keeping x-axis free) work for you? – Wolfgang Arnoldmy_breaks
function has any idea of whichcut
it is in. That information is not passed to it. – Ronak Shah