用于整数中断的 ggplot 函数(旧的解决方案不起作用)
ggplot function for integer breaks (old so solution not working)
library(tidyverse)
df <- tibble(col1 = c("A", "B"), col2 = c(0.4, 0.7))
#> # A tibble: 2 x 2
#> col1 col2
#> <chr> <dbl>
#> 1 A 0.4
#> 2 B 0.7
ggplot(df, aes(col1, col2)) + geom_col()
上面数据框的 ggplot 看起来像这样,其中包含十进制数字。
有多种方法可以从此 Whosebug question 指定整数分隔符。 None 他们似乎做我想做的事。我希望有两次休息,一次在 0
,一次在 1
。我如何修改以下这些功能之一来实现?
# Attempt 1
ggplot(df, aes(col1, col2)) +
geom_col() +
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() +
scale_y_continuous(breaks = scales::pretty_breaks(2))
# Attempt 3
ggplot(df, aes(col1, col2)) +
geom_col() +
scale_y_continuous(breaks = c(0, 1))
# Attempt 4
ggplot(df, aes(col1, col2)) +
geom_col() +
scale_y_continuous(
breaks = function(x) seq(ceiling(x[1]), floor(x[2]), by = 1))
# Attempt 5
ggplot(df, aes(col1, col2)) +
geom_col() +
scale_y_continuous(
breaks =
function(x, n = 5) pretty(x, n)[round(pretty(x, n),1) %% 1 == 0])
上面的大部分尝试都会产生下面的情节。 None生产我想要的。请注意缺少 1
的分隔符。
那是因为你的 y 轴不够远,看不到 1 处的中断,它实际上就在那里,只是你看不到而已:)
只需调整 y 轴限制即可解决此问题。
这是一个简单的解决方案:
ggplot(df, aes(col1, col2)) +
geom_col() +
scale_y_continuous(breaks = c(0, 1), limits = c(0, 1))
library(tidyverse)
df <- tibble(col1 = c("A", "B"), col2 = c(0.4, 0.7))
#> # A tibble: 2 x 2
#> col1 col2
#> <chr> <dbl>
#> 1 A 0.4
#> 2 B 0.7
ggplot(df, aes(col1, col2)) + geom_col()
上面数据框的 ggplot 看起来像这样,其中包含十进制数字。
有多种方法可以从此 Whosebug question 指定整数分隔符。 None 他们似乎做我想做的事。我希望有两次休息,一次在 0
,一次在 1
。我如何修改以下这些功能之一来实现?
# Attempt 1
ggplot(df, aes(col1, col2)) +
geom_col() +
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() +
scale_y_continuous(breaks = scales::pretty_breaks(2))
# Attempt 3
ggplot(df, aes(col1, col2)) +
geom_col() +
scale_y_continuous(breaks = c(0, 1))
# Attempt 4
ggplot(df, aes(col1, col2)) +
geom_col() +
scale_y_continuous(
breaks = function(x) seq(ceiling(x[1]), floor(x[2]), by = 1))
# Attempt 5
ggplot(df, aes(col1, col2)) +
geom_col() +
scale_y_continuous(
breaks =
function(x, n = 5) pretty(x, n)[round(pretty(x, n),1) %% 1 == 0])
上面的大部分尝试都会产生下面的情节。 None生产我想要的。请注意缺少 1
的分隔符。
那是因为你的 y 轴不够远,看不到 1 处的中断,它实际上就在那里,只是你看不到而已:) 只需调整 y 轴限制即可解决此问题。
这是一个简单的解决方案:
ggplot(df, aes(col1, col2)) +
geom_col() +
scale_y_continuous(breaks = c(0, 1), limits = c(0, 1))