gpt4 book ai didi

r - ggplot 轴限制的不对称扩展

转载 作者:行者123 更新时间:2023-12-02 05:54:10 25 4
gpt4 key购买 nike

如何在 ggplot 中不对称地调整限制的扩展?例如,

library(ggplot2)

ggplot(mtcars) +
geom_bar(aes(x = cyl), width = 1)

enter image description here

我希望条形的底部与面板背景的底部齐平,但仍然希望顶部有空间。我可以用空白注释来实现这一点:

ggplot(mtcars) + 
geom_bar(aes(x = cyl), width = 1) +
annotate("blank", x = 4, y = 16) +
scale_y_continuous(expand = c(0.0,0))

enter image description here

但是,在 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")

enter image description here

解决方案应该提供如下内容:

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))

enter image description here

最佳答案

ggplot2 v3.0.0 2018年7月发布有expand_scale()选项(w/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)))

enter image description here

关于r - ggplot 轴限制的不对称扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34623780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com