当制作具有不同y比例的多个ggplot2时,如何标准化binwidth?

时间:2019-05-23 20:19:36

标签: r loops for-loop ggplot2 graph

我有一些代码可以对数据中的所有变量进行绘制(36)并自动将其导出。它的效果很好,但是设置的binwidth很小。当我尝试更改bindwith时,根据它们的y轴比例,它对于我的图来说确实很小或很大。我怎样才能按比例增加所有人呢?

# Plot separate ggplot figures in a loop.
library(ggplot2)

# Make list of variable names to loop over.
var_list = combn(names(LessCountS)[1:37], 2, simplify=FALSE)
my_comparisons <- list( c("HC", "IN"), c("IN", "OUT"), c("HC", "OUT") )
symnum.args <- list(
  cutpoints = c(0.0001, 0.001, 0.01, 0.05, 1), 
  symbols = c("***", "**", "*", "NS")
)

# Make plots.
plot_list = list()
for (i in 1:37) {
  p = ggplot(LessCount1, aes_string(x=var_list[[i]][1], y=var_list[[i]][2])) +
    geom_dotplot(aes(fill= Type),
                 binaxis = "y",  stackratio = .5, binwidth = 90,
                 stackdir = "center"
    ) +
    theme_gray ()+
    labs(x="", y = "Cell Count (cells/\u03bcL)") +
    ggtitle(var_list[[i]][2]) +
    scale_x_discrete(labels=c("HC" = "Controls", "IN" = "Inpatients",
                              "OUT" = "Outpatients")) +
    theme(plot.title = element_text(hjust = 0.5, vjust = 2), legend.text=element_text(size=12),
          axis.text = element_text(size=14),
          axis.title = element_text(size = 14)) +
    scale_fill_manual(values=c("#CCCCCC", "#990066", "#3366CC")) +
    stat_summary(fun.y = median, fun.ymin = median, fun.ymax = median,
                 geom = "crossbar", width = 0.5, size = .45) +
      stat_compare_means(comparisons = my_comparisons, label.y = , label = "p.signif", size = 5, symnum.args = symnum.args) +
    stat_compare_means(label.y = )

  plot_list[[i]] = p
}

# Save plots to tiff. Makes a separate file for each plot.
for (i in 1:37) {
  file_name = paste("LessCount1_plot_", var_list[[i]][2], ".tiff", sep="")
  tiff(file_name)
  print(plot_list[[i]])
  dev.off()
}

结果示例如果,我更改了bindwidthenter image description here enter image description here

如果我未指定binwidth,则它们的大小相同,但是非常小。我希望无论规模大小,都按比例增加它,希望这是可能的!

预先感谢, S

1 个答案:

答案 0 :(得分:0)

您需要使binwidth以数据为条件,而不是将其设置为固定值。这是一个示例:

library("ggplot2")

for (ii in 1:5) {
    y <- names(mtcars)[ii]
    p <- ggplot(mtcars, aes(x = 1, y = !!sym(y))) +
        geom_dotplot(binaxis = "y", stackdir = "center",
                     # binwidth = 1
                     binwidth = diff(range(mtcars[, y]))/20)
    print(p)
}