简体   繁体   中英

scale_x/y_continuous breaks by n in R ggplot2?

I have some plots where I want to break the x or/and y axes by different n's. In order to achieve this I have a dozen of functions like:

by_two <- function(x) {

  seq(0, max(x), by = 2)

}

Which I pass for each plot:

p1 <- ggplot(users_d_total %>% filter(isSame, D_rank == 2), aes(x = D, fill = as.factor(train_user_id))) +
  geom_density(alpha = .3) +
  labs(title = paste0("Without Normalization Analysis [K = 2]")) + 
  scale_fill_discrete(name = "Users") +
  scale_x_continuous(breaks = by_two)

When I try to do it simpler:

by_n <- function(x,n) {

      seq(0, max(x), by = n)

    }

But when I pass by_n with n = 0.5 or 1 or any other positive number I get an error for wrong type.

p1 <- ggplot(users_d_total %>% filter(isSame, D_rank == 2), aes(x = D, fill = as.factor(train_user_id))) +
  geom_density(alpha = .3) +
  labs(title = paste0("Without Normalization Analysis [K = 2]")) + 
  scale_fill_discrete(name = "Users") +
  scale_x_continuous(breaks = by_n(1))

Please advise how to make this smarter solution feasible.

I don't know how to limit the sequence to the range of the given data, but I'm not sure it's necessary since ggplot only uses the range of the data anyway.

#  Hacky, but ggplot ignores breaks beyond what's needed for the data
by_n <- function(n) { seq(0, 1000, by = n) }

ggplot(iris, 
       aes(x = Sepal.Length,
           fill = Species)) +
  geom_density(alpha = .3) +
  labs(title = paste0("Without Normalization Analysis [K = 2]")) + 
  scale_fill_discrete(name = "Users") +
  scale_x_continuous(breaks = by_n(0.5))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM