【问题标题】:Loop ggplot for different variables in dataframe为数据框中的不同变量循环ggplot
【发布时间】:2017-07-09 13:37:38
【问题描述】:

我想循环 ggplot 并获取每个变量代码的图表如下。我在aes 中收到错误

df <- data.frame(ID = c("a", "b"), A = rnorm(2), B = runif(2), C = rlnorm(2))
for(i in df[,2:ncol(df)]){
 plt<-ggplot(data=df, aes(x=df$ID, y = df[,2:ncol(df)]$i))+
    geom_bar()
  print(plt)
}

有什么问题?

我知道我可以使用facet_grid

ggplot(df_melt, aes(x=ID,y=value)) + geom_bar(stat="identity") + facet_grid(~variable)

【问题讨论】:

    标签: r loops ggplot2


    【解决方案1】:
    df <- data.frame(ID = c("a", "b"), A = rnorm(2), B = runif(2), C = rlnorm(2))
    
    for (colname in names(df)[-1]) {
      plt <- ggplot(data = df, aes_string("ID", y = colname)) +
        geom_bar(stat = "identity")
      print(plt)
    }
    

    【讨论】:

    • 请注意,您现在可以将geom_bar(stat = "identity") 替换为geom_col()
    猜你喜欢
    • 1970-01-01
    • 2015-01-15
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多