Reputation: 4040
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.
Upvotes: 0
Views: 555
Reputation: 66490
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))
Upvotes: 2