【问题标题】:customising title of plots from loops in r从 r 中的循环中自定义绘图的标题
【发布时间】:2020-06-10 15:03:22
【问题描述】:

我创建了一个循环来:1)根据season 变量为每列生成百分比;和 2) 将百分比绘制成堆积条形图。

我想做两件事:1) 代替df[[b]] 作为输出df_percent 的第一列的名称,而是使用循环的实际列名称;和 2) 用循环的列名标记绘图的 x 轴

这是我用我的代码得到的最远距离:

colNames <- names(df)[-c(1,2,7,9,10,12,37,38,63,65,74,76,79,75,77,14,42,64,69,8,49,58,60,78)]
for(b in colNames){
  df_percent <- df %>% group_by(df[[b]]) %>% count(season) %>% mutate(Percent=n/sum(n)) %>% mutate(Percentage = round(Percent*100, digits=2)) %>% as.data.frame()
  print(df_percent)
  plt_pc <- ggplot(df_percent, aes(x=df_percent[,1], y=df_percent$Percentage, fill=df_percent$season)) +
    geom_bar(stat="identity") + geom_text(aes(label=round(Percentage)), position = position_stack(vjust = 0.5), size=3) + labs(y="Percentage (%)", title="Percentage Calculation", fill="season", x=df[[b]])
  print(plt_pc)
}

对于df_percent,我尝试过names(df_percent) = "df[[b]]",但这无助于更改第一列的名称df_percent。对于该图,x=IPS[[b]] 从循环的列中给出一个随机值,并尝试为所有图的 x=paste0(colNames) 标记 x 轴,其中标题为循环的第一列。

有人知道如何解决这个问题吗?

【问题讨论】:

    标签: r loops for-loop ggplot2 dplyr


    【解决方案1】:

    如果没有可重复的示例,很难知道,但我认为这可以满足您的需求:

    for(b in colNames){
      df_percent <- df %>% 
        group_by(!!!b) %>% 
        count(season) %>% 
        mutate(Percent=n/sum(n)) %>% 
        mutate(Percentage = round(Percent*100, digits=2)) %>% 
        as.data.frame()
      print(df_percent)
    
      plt_pc <- ggplot(df_percent, aes(x=df_percent[,1], y=Percentage, fill=season)) +
        geom_bar(stat="identity") + 
        geom_text(aes(label=round(Percentage)), position = position_stack(vjust = 0.5), size=3) + 
        labs(y="Percentage (%)", title="Percentage Calculation", fill="season", x=b)
      print(plt_pc)
    }
    

    【讨论】:

    • 感谢@sparrow 的解决方案!对于 plt_pc 使用 labs(x=b) 解决了绘图的 x 轴标记。对于df_percent,使用group_by(!!!b) 可以保留列名。我也尝试了group_by(.data[[b]]),这也有效。
    • 酷。如果可行,请考虑 accepting the answer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 2020-09-02
    • 2023-03-02
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多