繁体   English   中英

从 r 中的循环自定义绘图标题

[英]customising title of plots from loops in r

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

我想做两件事:1)代替df[[b]]作为 output df_percent的第一列的名称,以获得循环的实际列名称; 和 2) 到 label 的 X 轴 plot 的列名称是循环的

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

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的第一列名称。 对于 plot, x=IPS[[b]]给出循环列中的随机值,并尝试x=paste0(colNames)为所有图标记 x 轴,其中 header 用于循环的第一列。

任何人都知道如何解决这个问题?

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

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)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM