简体   繁体   English

R ggplot2:将列的值放在堆叠条的顶部

[英]R ggplot2: place value of column on top of stacked bars

There might be a duplicate, but I do not find an answer that applies to my particular case...可能有重复,但我没有找到适用于我的特定情况的答案......

I just have a very simple data frame like the one below, with counts in two columns ( Number_NonHit_Cells , Number_Hit_Cells ) that I want to show in stacked bars, having the value of another column ( Freq ) placed on top of the stacked bars.我只有一个非常简单的数据框,如下所示,有两列( Number_NonHit_CellsNumber_Hit_Cells )的计数,我想在堆叠条中显示,将另一列( Freq )的值放在堆叠条的顶部。

The MWE below is the best I have been able to get so far, but I only need the value of Freq once, and at the very top of the bars combined...下面的 MWE 是迄今为止我所能得到的最好的,但我只需要一次Freq的值,并且在条形的最顶部合并......

It would even be better if Freq could be calculated inside the ggplot2 call.如果可以在ggplot2调用中计算Freq ,那就更好了。

This is my MWE:这是我的 MWE:

  clono_df_long <- data.frame(Clonotype=LETTERS[1:5], Number_Hit_Cells=c(234,56,568,34,46),
                              Number_NonHit_Cells=c(c(52,12,234,21,31)))
  clono_df_long$Clonotype_Size <- clono_df_long$Number_Hit_Cells+clono_df_long$Number_NonHit_Cells
  clono_df_long$Freq <- round(clono_df_long$Number_Hit_Cells/clono_df_long$Clonotype_Size,4)*100
  clono_df_long <- as.data.frame(tidyr::pivot_longer(clono_df_long,
                                                     -c(Clonotype,Clonotype_Size,Freq),
                                                     names_to = "Cells", values_to = "Value"))
  clono_df_long$Clonotype <- factor(clono_df_long$Clonotype, levels=unique(clono_df_long$Clonotype))
  clono_df_long$Cells <- factor(clono_df_long$Cells, levels=c('Number_NonHit_Cells','Number_Hit_Cells'))
  P <- ggplot2::ggplot(clono_df_long, ggplot2::aes(x=Clonotype, y=Value, fill=Cells)) +
    ggplot2::geom_bar(stat="identity") +
    ggplot2::scale_fill_manual(values=c('gray70', 'gray40')) +
    ggplot2::geom_text(ggplot2::aes(label=paste0(Freq,'%')), vjust=-1) +
    ggplot2::theme_light()
  grDevices::pdf(file='test.pdf', height=6, width=6)
  print(P)
  grDevices::dev.off()

Which produces this:产生这个:

测试

You may try你可以试试

clono_df_long$Freq <- ifelse(clono_df_long$Cells == "Number_NonHit_Cells", clono_df_long$Freq, NA)

ggplot2::ggplot(clono_df_long, ggplot2::aes(x=Clonotype, y=Value, fill=Cells)) +
  ggplot2::geom_bar(stat="identity") +
  ggplot2::scale_fill_manual(values=c('gray70', 'gray40')) +
  #ggplot2::geom_text(ggplot2::aes(label=paste0(Freq,'%')), vjust=-1) +
  ggplot2::theme_light() +
  ggplot2::geom_text(aes(label = scales::percent(Freq/100) ),position = "stack") 
  

在此处输入图片说明

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

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