Display name
Display name

Reputation: 4481

ggplot only show positive values on y-axis (faceted plot)

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:

  1. Don't display any (-) 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.
  2. Keep scales = "free"
  3. Keep the expanded scale as well

How do I do it?

facet delete negative

Upvotes: 1

Views: 1809

Answers (1)

markus
markus

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)

enter image description here

Upvotes: 3

Related Questions