0

i am trying to label/annotate my bar-chart with its corresponding percentage difference value.

Current Barchart: enter image description here

I found this tutorial and decided to copy it as reference:

https://www.r-bloggers.com/2021/09/adding-text-labels-to-ggplot2-bar-chart/

  for (indexName in IndexNames){
    #Calculate Percentage difference
    #Cg2300 < Cg2400 < GB1U < Dell
    CG2400Dif <- ((CG2400DF[indexName] - CG2300DF[indexName])/CG2300DF[indexName]) * 100
    #Get orig values in list
    values <- data.frame(
      serverType <- c("CG2300","CG2400","Dell"),
      result <- c(CG2300DF[indexName],CG2400DF[indexName],DellDF[indexName]),
      percentDiff <- c(CG2400Dif,CG2400Dif,0)
    )
    p<-ggplot(data=values, aes(x=serverType, y=result,fill=serverType)) +
      geom_bar(stat="identity")+theme_minimal()+
      xlab("Server Type")+
      ylab(UnitNames)+
      ggtitle(BarChartNames)+
      geom_text(aes(label= ..percentDiff..), stat = "percentDiff", vjust = 1.5, colour = "white")
    print(p)
  }
}

I get this error:

Error in `check_subclass()`:
! Can't find `stat` called 'percentDiff'
Run `rlang::last_error()` to see where the error occurred.
Ruth Edges
  • 137
  • 10
  • Try with `geom_text(aes(label= percentDiff), vjust = 1.5, colour = "white")`. In the blogpost the author had to compute the counts using `stat="count"` and refer to this computed value using `..count..`. In your case `percentDiff` is a column of your df so that's not necessary. – stefan Feb 21 '22 at 19:00
  • @stefan Error: Discrete value supplied to continuous scale – Ruth Edges Feb 22 '22 at 08:46
  • Hm. From your code I don't see any reason for this error. But I'm quite sure that this is not related to the issue with the labels. To help us to help you I would suggest to provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. We don't need all of you data. Just an example for e.g. one of your `IndexNames` – stefan Feb 22 '22 at 09:54

0 Answers0