【问题标题】:Saving unique ggplots based on ID variable根据 ID 变量保存唯一的 ggplots
【发布时间】:2019-03-18 20:13:35
【问题描述】:

我正在尝试使用循环通过 ID 号创建和保存单个图表。我不确定我是否做错了循环,或者它是否与数据设置有关。我最终得到的图上绘制了两个 ID 的数据,但根据 ggsave 命令定义的名称保存了两次。我觉得我错过了一些简单的东西。

我使用的数据是这样的:

df <- data.frame(ID = c(1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2), 
                   Time = c("1","2", "1", "2", "1", "2", "1", "2", "1", "2", "1", "2"), 
                   Category = c("Red", "Red", "Red", "Red", "Blue", "Blue", "Blue", "Blue", "Yellow","Yellow", "Yellow", "Yellow"), 
                   Score = c(0, 0, 0, 0, 1, 2, 0, 3, 1, 1, 3, 2))

这是我的代码:

idlist <-unique(df$ID)

for (i in idlist) {
  plot<- df %>%
    ggplot(aes(x=Category, y=as.numeric(Score), fill=Time))+
    geom_bar(color="black", stat="identity", position=position_dodge(.8), width=0.75)+
    geom_text(aes(x=Category, y=Score,label=Score), position=position_dodge(width=1), hjust=0.5, vjust=-.25, size=3)+
    labs(x="Category",y="Score")

  ggsave(filename=paste("plot",id[i],".png",sep=""), plot,
         device = function(...) png(..., units="in",res=200))
}

【问题讨论】:

  • 您实际上并没有按 id 过滤任何内容。所有图表都将完全相同。
  • 为此:id[i],你在哪里定义了id

标签: r loops for-loop ggplot2


【解决方案1】:

只需在循环中添加 filter 即可在当前循环 ID 上构建图:

idlist <-unique(df$ID)

for (i in idlist) {
  plot <- df %>%
    filter(ID == i) %>%
    ggplot(aes(x=Category, y=as.numeric(Score), fill=Time)) +
    geom_bar(color="black", stat="identity", 
             position=position_dodge(.8), width=0.75) +
    geom_text(aes(x=Category, y=Score, label=Score), 
              position=position_dodge(width=1), hjust=0.5, vjust=-.25, size=3) +
    labs(x="Category", y="Score")

  ggsave(filename=paste("plot",  i, ".png", sep=""), plot,
         device = function(...) png(..., units="in", res=200))
}

或者,使用基本 R 的 by 并避免显式 for 循环和 unique() 调用:

by(df, df$ID, function(sub) {
  plot <- ggplot(sub, aes(x=Category, y=as.numeric(Score), fill=Time)) +
            geom_bar(color="black", stat="identity", 
                     position=position_dodge(.8), width=0.75) +
            geom_text(aes(x=Category, y=Score, label=Score), 
                      position=position_dodge(width=1), hjust=0.5, vjust=-.25, size=3) +
            labs(x="Category", y="Score")

  ggsave(filename=paste0("plot", sub$id[[1]], ".png"), plot,
         device = function(...) png(..., units="in", res=200))
})

【讨论】:

    猜你喜欢
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 2022-09-23
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    相关资源
    最近更新 更多