DaniCee
DaniCee

Reputation: 3217

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.

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...

It would even be better if Freq could be calculated inside the ggplot2 call.

This is my 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:

test

Upvotes: 1

Views: 964

Answers (1)

Kra.P
Kra.P

Reputation: 15153

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

enter image description here

Upvotes: 2

Related Questions