1

我正在为一篇论文创建一些收获图,并且在代码上有些磕磕绊绊。我使用“钻石”重新创建了重要的部分,以便人们更容易重新创建

第1部分

目的是创建一个由多个变量组成的条形图,例如“克拉”和“颜色”,因为它们将作为图的标题。我使用 ggforce 的分页来允许我将其分布在多个页面上,因为我希望每个页面按组显示结果 - 在这里我为每个页面添加了值 '1'、'2' 或 '3'数据框的行。虽然我可以对数据框进行子集化并单独创建图,但问题是页面之间的条形宽度不一致,即使我将 width = x 添加到 geom_bar (尽管每个页面中的宽度相同)。

有谁知道我如何做到这一点?我想知道 aes_string 是否会有所帮助,但不确定它是否适用于我需要的多个方面。

第 2 部分 当我尝试添加一些代码来保存图像时,它会覆盖 grid.arrange ... 命令以指定绘图大小(因此它们都是一致的)并进行调整以填充空白。这很容易解决吗?

谢谢,卡尔

library(ggplot2)
library(ggforce)
library(plyr)
library(dplyr)
library(grid)
library(egg)

df = diamonds
df$Group<- rep(1:3,length.out=nrow(df))

for (i in df$Group) {

  p <- ggplot(data=df, aes(x=cut, y=clarity, fill=price)) +
    # preserve = single keeps all bars same width, rather than adjusting to 
    # the space
    geom_bar(position=position_dodge2(preserve = 'single'),
             stat="identity", color = "black", size = 0.2) + 
    # paginate allows the chart to be printed on multiple pages
    # strip position adds facet title to top of page
    facet_wrap_paginate(c("carat","color"), ncol = 3, nrow = 3,
                        scales = "fixed", strip.position = "top", page = i)


  # manually adjust the size of the plot panels
  grid.arrange(grobs = lapply(
    list(p),
    set_panel_size,
    width = unit(8,"cm"),
    height = unit(5,"cm")
  ))
}
4

0 回答 0