Ale*_*lex 5 size r width ggplot2 geom-bar
我在循环中生成了几个条形图,它们都根据输出大小(从绘图/设备大小假设?)而不是根据条形大小调整大小。这意味着具有两个条形的图具有粗条,而具有 6 个条的图具有细条;不过,两个输出的大小相同。下面的代码表示我的脚本具有可复制的数据(我对我的做了许多其他 aes/主题更改)。
我希望输出图调整大小(在条形宽度的维度上),以便条形在不同的图形中始终具有相同的宽度,但输出图像根据(相同宽度)条形的数量改变大小。
my_factors = c("vs","cyl","carb")
for (current_factor in my_factors) {
c <- ggplot(mtcars, aes(factor(current_factor)))
c + geom_bar() + coord_flip()
ggsave(paste0(my_factors(current_factor),".png")
}
Run Code Online (Sandbox Code Playgroud)
对不起,如果我错过了一些明显的东西,我是 ggplot 和 R 的新手。我来自 MATLAB,所以整个“设备”的事情仍然让我感到困惑!在 MATLAB 中,我会明确指定条形大小(即不是相对的),并且输出会相应地调整大小。
你可以使用这个foo功能
library(lazyeval)
library(ggplot2)
foo <- function(data,i, height_rate = 0.1){
height <- eval(substitute(length(unique(data$i))))
ld <- as.lazy_dots(list(lazy(i)))
ld <- as.lazy_dots(lapply(ld, function(x){
try(x$expr <- as.name(x$expr), silent=TRUE)
x
}))
x <- make_call(quote(aes),make_call(quote(factor),ld))
ggplot(data, eval(x$expr))+
geom_bar(width = height_rate*height)+
coord_flip()
}
foo(mtcars,"cyl")
Run Code Online (Sandbox Code Playgroud)
因为lazyeval包
foo(mtcars,cyl)
Run Code Online (Sandbox Code Playgroud)
也有效。此代码的一个缺点是仅使用列的确切名称。因此,为了使用for循环代码,必须进行一些开发。希望能帮助到你。