当我在ggplot2中绘制条形图时,我想将条形底部和x轴之间的空间减小到0,同时保持条形图和绘图框上方的空间.我有一个黑客在下面这样做.它很脏,我想再次清洁.有没有办法在没有肮脏的小黑客的情况下实现这种行为?
默认(上面所需的空格但不希望空格下方的空格):
ggplot(mtcars, aes(x=as.factor(carb))) +
geom_bar()
Run Code Online (Sandbox Code Playgroud)

使用展开(上面不需要的0空格但是在条形下面有0个空格):
ggplot(mtcars, aes(x=as.factor(carb))) +
geom_bar() +
scale_y_continuous(expand = c(0,0))
Run Code Online (Sandbox Code Playgroud)

肮脏的黑客(我喜欢它,但它......好吧,脏):
ggplot(mtcars, aes(x=as.factor(carb))) +
geom_bar() +
scale_y_continuous(expand = c(0,0)) +
geom_text(aes(x=1, y=10.3, label="Stretch it"), vjust=-1)
Run Code Online (Sandbox Code Playgroud)

如何在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))) …Run Code Online (Sandbox Code Playgroud) 我有一些数据共享一个共同的 x 轴,但有两个不同的 y 变量:
set.seed(42)
data = data.frame(
x = rep(2000:2004, 2),
y = c(rnorm(5, 20, 5), rnorm(5, 150, 15)),
var = rep(c("A", "B"), each = 5)
)
Run Code Online (Sandbox Code Playgroud)
我正在使用分面线图来显示数据:
p = ggplot(data, aes(x, y)) +
geom_line() +
facet_grid(var ~ ., scales = "free_y")
Run Code Online (Sandbox Code Playgroud)
我希望 y 轴包含 0。这很容易:
p + expand_limits(y = 0)
Run Code Online (Sandbox Code Playgroud)
但随后我的数据看起来过于拥挤,离我的方面的顶部太近了。所以我想填充轴的范围。通常scale_y_continuous(expand = ...)用于填充轴,但填充对称地应用于顶部和底部,使 y 轴远低于0。
p + expand_limits(y = 0) +
scale_y_continuous(expand = c(0.3, 0.2))
# the order of expand_limits and scale_y_continuous
# …Run Code Online (Sandbox Code Playgroud)