如何在ggplot中非对称地调整限制的扩展?例如,
library(ggplot2)
ggplot(mtcars) +
geom_bar(aes(x = cyl), width = 1)
我希望条形图的底部与面板背景的底部齐平,但仍希望在顶部留出空间。我可以使用空白注释来实现:
ggplot(mtcars) +
geom_bar(aes(x = cyl), width = 1) +
annotate("blank", x = 4, y = 16) +
scale_y_continuous(expand = c(0.0,0))
但是,在早期版本的
ggplot
中,我可以使用the solution provided by Rosen Matev:library("scales")
scale_dimension.custom_expand <- function(scale, expand = ggplot2:::scale_expand(scale)) {
expand_range(ggplot2:::scale_limits(scale), expand[[1]], expand[[2]])
}
scale_y_continuous <- function(...) {
s <- ggplot2::scale_y_continuous(...)
class(s) <- c('custom_expand', class(s))
s
}
然后使用
scale_y_continuous(expand = list(c(0,0.1), c(0,0)))
将为图表顶部添加一致的添加项。但是,在当前版本中,出现错误ggplot(mtcars) +
geom_bar(aes(x = cyl), width = 1) +
scale_y_continuous(expand = list(c(0,0.1), c(0,0)))
# Error in diff(range) * mul : non-numeric argument to binary operator
ggplot2 2.0是否有有效的解决方案?
解决方案应该包括灵活使用方面的功能以及
free_xy
缩放选项。例如,ggplot(mtcars) +
geom_bar(aes(x = cyl, fill = factor(vs)), width = 1) +
facet_grid(vs ~ ., scales = "free_y")
解决方案应提供以下内容:
ggplot(mtcars) +
geom_bar(aes(x = cyl, fill = factor(vs)), width = 1) +
facet_grid(vs ~ ., scales = "free_y") +
scale_y_continuous(expand = c(0,0)) +
geom_blank(data = data.frame(cyl = c(5,5), y = c(12, 16), vs = c(1,0)), aes(x = cyl, y = y))
最佳答案
2018年7月发布的 ggplot2 v3.0.0
具有 expand_scale()
选项(带有mult
参数)以实现OP的目标。
编辑:expand_scale()
将在将来的版本中弃用,而改为expansion()
。有关更多信息,请参见News。
library(ggplot2)
### ggplot <= 3.2.1
ggplot(mtcars) +
geom_bar(aes(x = cyl, fill = factor(vs)), width = 1) +
facet_grid(vs ~ ., scales = "free_y") +
scale_y_continuous(expand = expand_scale(mult = c(0, .2)))
### ggplot >= 3.2.1.9000
ggplot(mtcars) +
geom_bar(aes(x = cyl, fill = factor(vs)), width = 1) +
facet_grid(vs ~ ., scales = "free_y") +
scale_y_continuous(expand = expansion(mult = c(0, .2)))
关于r - ggplot轴限制的不对称扩展,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34623780/