自动调整ggplot中的条的大小以在多个图形R中保持一致 [英] Automatically resize bars in ggplot for uniformity across several graphs R

查看:350
本文介绍了自动调整ggplot中的条的大小以在多个图形R中保持一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个循环中生成了几个条形图,它们都根据输出大小(假设是从图/设备大小来确定大小),而不是根据条形大小进行调整.这意味着具有两个条形的地块具有粗条,而具有6条形的地块具有细条.但是,两个输出的大小相同.下面的代码用可复制的数据代表了我的脚本(我对我的许多其他aes/主题进行了更改).

I generate several bars graphs in a loop, and they all resize according to the output size (assume from plot/device size?) rather than according to the bar size. This means that plots with two bars have fat bars, and plots with, say, 6 bars, have thin bars; both outputs are the same size though. The code below represents my script with reproduceable data (I do many other aes/theme changes to mine).

我希望调整输出图的大小(以条宽度为单位),以使条在不同图形上的宽度始终相同,但是输出图像会根据(相同宽度)条的数量而改变大小.

I'd like the output plot to resize (in the dimension of bar width) so that the bars are always the same width across different graphs, but the output images change size according to the number of (same width) bars.

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

对不起,如果我错过了耀眼的事物,我是ggplot和R的新手.我来自MATLAB,所以整个设备"问题仍然让我感到困惑!在MATLAB中,我会明确指定条形大小(即不相对),并且输出将相应地调整大小.

Sorry if I've missed something glaring, I am new to ggplot, and R. I'm from MATLAB so the whole "device" thing still confuses me! In MATLAB I'd specify the bar size explicitly (i.e. not relatively), and the output would resize accordingly.

推荐答案

您可以使用此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")

由于lazyeval

foo(mtcars,cyl)

也可以.此代码的缺点是只能使用列的确切名称.因此,为了使用for循环代码,必须进行一些开发.希望对您有所帮助.

also works.A disadvantage of this code is usage only exact name of column. So in order to use for loop code has to be developed a bit. Hope it helps.

这篇关于自动调整ggplot中的条的大小以在多个图形R中保持一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆