问题描述
你如何在ggplot中非对称地调整限制的扩展?例如,
library(ggplot2)
ggplot(mtcars)+
geom_bar( aes(x = cyl),width = 1)
在以前的版本中 ggplot
,但是,我可以使用
解决方案应该提供类似于:
ggplot(mtcars)+
geom_bar(aes(x = cyl,fill = factor(vs)),width = 1)+
facet_grid(vs〜。, scale =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))
来实现OP的目标编辑:你实际上需要开发版本的 ggplot2 2.2.1.9000
。运行
devtools :: install_github(tidyverse / ggplot2)
来安装。
<$ p (aes(x = cyl,fill = factor(vs)),width = 1); $ p> library(ggplot2)
ggplot(mtcars)+
geom_bar +
facet_grid(vs〜。,scales =free_y)+
scale_y_continuous(expand = expand_scale(mult = c(0,.2)))
How do you adjust the expansion of limits asymmetrically in ggplot? For example,
library(ggplot2)
ggplot(mtcars) +
geom_bar(aes(x = cyl), width = 1)
I would like the bottom of the bars flush with the bottom of the panel background, but would still like space at the top. I can achieve this with a blank annotation:
ggplot(mtcars) +
geom_bar(aes(x = cyl), width = 1) +
annotate("blank", x = 4, y = 16) +
scale_y_continuous(expand = c(0.0,0))
In previous versions of ggplot
, however, I could use 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
}
and then use scale_y_continuous(expand = list(c(0,0.1), c(0,0)))
which would add a consistently addition to the top of the chart. In the current version, however, I get an error
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
Is there an effective solution for ggplot2 2.0?
A solution should include the ability to work flexibly with facets, and free_xy
scale options. For example,
ggplot(mtcars) +
geom_bar(aes(x = cyl, fill = factor(vs)), width = 1) +
facet_grid(vs ~ ., scales = "free_y")
A solution should provide something like:
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))
With ggplot2 2.2.1
, we can now use expand_scale
to achieve OP's goal
Edit: you actually need the development version of ggplot2 2.2.1.9000
. Rundevtools::install_github("tidyverse/ggplot2")
to install.
library(ggplot2)
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轴限制的不对称扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!