如何在ggplot中不对称地调整限制的扩展?例如,
library(ggplot2)
ggplot(mtcars) +
geom_bar(aes(x = cyl), width = 1)
Run Code Online (Sandbox Code Playgroud)
我希望条形图的底部与面板背景的底部齐平,但仍然需要顶部的空间.我可以使用空白注释来实现此目的:
ggplot(mtcars) +
geom_bar(aes(x = cyl), width = 1) +
annotate("blank", x = 4, y = 16) +
scale_y_continuous(expand = c(0.0,0))
Run Code Online (Sandbox Code Playgroud)
ggplot但是,在以前的版本中,我可以使用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
}
Run Code Online (Sandbox Code Playgroud)
然后使用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
Run Code Online (Sandbox Code Playgroud)
ggplot2 2.0有效吗?
解决方案应该包括灵活地使用构面和free_xy缩放选项的能力.例如,
ggplot(mtcars) +
geom_bar(aes(x = cyl, fill = factor(vs)), width = 1) +
facet_grid(vs ~ ., scales = "free_y")
Run Code Online (Sandbox Code Playgroud)
解决方案应该提供如下内容:
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))
Run Code Online (Sandbox Code Playgroud)
Tun*_*ung 19
ggplot2 v3.0.02018年7月发布的expand_scale()选项(w/multargument)可以实现OP的目标
library(ggplot2)
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)))
Run Code Online (Sandbox Code Playgroud)
我现在尝试为此添加代码ggplot2; 请参阅问题#1669和相应的拉取请求.如果它被接受,则expand参数的语法将从更改c(m, a)为c(m_lower, a_lower, m_uppper, a_upper),用于为较低和较高范围限制指定单独的扩展值.(旧的语法仍将继续工作,因为如果缺少元素3和/或4,前两个元素将被重用.)
使用这种新语法,您可以使用
ggplot(mtcars) +
geom_bar(aes(x = cyl), width = 1) +
scale_y_continuous(expand = c(0, 0, 0.05, 0))
Run Code Online (Sandbox Code Playgroud)
结果如下:
它也适用于facetting:
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, 0.05, 0))
Run Code Online (Sandbox Code Playgroud)