library(tidyverse)
df <- tibble(col1 = rep(c("A", "B"), 2),
col2 = c(0.4, 0.7, 3, 9),
col3 = c("I", "I", "II", "II"))
#> # A tibble: 4 x 3
#> col1 col2 col3
#> <chr> <dbl> <chr>
#> 1 A 0.4 I
#> 2 B 0.7 I
#> 3 A 3 II
#> 4 B 9 II
ggplot(df, aes(col1, col2)) +
geom_col() +
facet_wrap(vars(col3), scales = "free")
我想为上面的 ggplot 创建整数中断,以便:
对于我的第一个方面
I
轴的整数值将包括 0
和 1
.对于第二个方面 II
整数值应包括在最小值 0
处并且最大整数必须至少为 9
,也许 10
会更好看,这取决于用于创建中断的例程。这些尝试来自此 older stackoverflow question不太工作。
# Attempt 1
ggplot(df, aes(col1, col2)) +
geom_col() +
facet_wrap(vars(col3), scales = "free") +
scale_y_continuous(
breaks = function(x) unique(floor(pretty(seq(0, (max(x) + 1) * 1.1)))))
# Attempt 2
ggplot(df, aes(col1, col2)) +
geom_col() +
facet_wrap(vars(col3), scales = "free") +
scale_y_continuous(breaks = scales::pretty_breaks(2))
# Attempt 3
ggplot(df, aes(col1, col2)) +
geom_col() +
facet_wrap(vars(col3), scales = "free") +
scale_y_continuous(breaks = c(0, 1))
# Attempt 4
ggplot(df, aes(col1, col2)) +
geom_col() +
facet_wrap(vars(col3), scales = "free") +
scale_y_continuous(
breaks = function(x) seq(ceiling(x[1]), floor(x[2]), by = 1))
# Attempt 5
ggplot(df, aes(col1, col2)) +
geom_col() +
facet_wrap(vars(col3), scales = "free") +
scale_y_continuous(
breaks =
function(x, n = 5) pretty(x, n)[round(pretty(x, n),1) %% 1 == 0])
大多数尝试会产生类似以下内容。注意丢失的
1
打破第一方面。我希望第二个方面在 10
休息一下.我不想手动设置限制或中断,因为实际上我有数百个方面。希望可以修改上述功能之一以满足我的要求。最佳答案
要获得所需的结果,您还必须调整 y 轴的限制。尝试这个:
library(tidyverse)
df <- tibble(col1 = rep(c("A", "B"), 2),
col2 = c(0.4, 0.7, 3, 9),
col3 = c("I", "I", "II", "II"))
my_ceil <- function(x) {
ceil <- ceiling(max(x))
ifelse(ceil > 1 & ceil %% 2 == 1, ceil + 1, ceil)
}
my_breaks <- function(x) {
ceil <- my_ceil(max(x))
unique(ceiling(pretty(seq(0, ceil))))
}
my_limits <- function(x) {
ceil <- my_ceil(x[2])
c(x[1], ceil)
}
ggplot(df, aes(col1, col2)) +
geom_col() +
facet_wrap(vars(col3), scales = "free") +
scale_y_continuous(breaks = my_breaks, limits = my_limits)
创建于 2020-05-21 由 reprex package (v0.3.0)
关于r - ggplot 整数中断方面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61915427/