Reputation: 4481
library(tidyverse)
mpg2 <- mpg %>% mutate(hwy = hwy - 30)
ggplot(mpg2, aes(cty, hwy)) +
geom_point() +
facet_grid(year ~ fl, scales = "free") +
scale_y_continuous(expand = expand_scale(mult = 2))
With the code chunk above I'd like to do three things simultaneously:
(-)
negative y-axis labels (in my example you'd need to delete the -40
, -30
, and -60
labels). I only want zero and positive labels to show. scales = "free"
How do I do it?
Upvotes: 1
Views: 1809
Reputation: 26343
We can pass a function to the breaks argument in scale_y_continuous
that returns a numeric vector of length two, in this case.
library(ggplot2); library(dplyr)
mpg2 <- mpg %>% mutate(hwy = hwy - 30)
my_breaks <- function(x) c(0, (((max(x) / 2) %/% 10) + 1) * 10)
The function outputs 0
and (((max(x) / 2) %/% 10) + 1) * 10
which gives OP's desired output. The upper break is the maximum of y
divided by 2
and 'rounded up' to the next larger multiple of 10
.
Example
my_breaks(67)
# [1] 0 40
Plot
ggplot(mpg2, aes(cty, hwy)) +
geom_point() +
facet_grid(year ~ fl, scales = "free") +
scale_y_continuous(expand = expand_scale(mult = 2),
breaks = my_breaks)
Upvotes: 3