Vint
Vint

Reputation: 499

Adding text to a ggplot bar plot by group within a function

Given a dataset like this:

XX<-as.factor(c('P','P','P','R','R','R','F','F','F'))
YY<-c(2,3,6,3,5,3,2,3,4)
Facto<-c("A","B","C","A","B","C","A","B","C")
Text<-c("Z","Z","F","Z","H","Z","Z",'Z',"M")
MyData<-data.frame(XX,YY,Facto,Text)
rm(Facto)

My goal is to have a function to create a bar chart with text above each bar

MyBarPlot<-function(Data, ColName){
  dodger = position_dodge(width = 0.9)
  ggplot(Data, aes(x=XX, y=YY, fill=Facto))+
    geom_bar(stat="identity", color="black",position=position_dodge())+
    scale_fill_viridis(discrete = TRUE,option = "D",name=)+
    geom_text(aes(label=Text, group = ColName), position = dodger, col='red')+
    theme_minimal()
  
  
}

When I run the above function, the "fill=" argument works just fine, but the "group by" aspect for geom_text does not.

MyBarPlot(MyData,'Facto')

If I change the "group=" line in the function like this:

MyBarPlot<-function(Data, ColName){
      dodger = position_dodge(width = 0.9)
      ggplot(Data, aes(x=XX, y=YY, fill=Facto))+
        geom_bar(stat="identity", color="black",position=position_dodge())+
        scale_fill_viridis(discrete = TRUE,option = "D",name=)+
        geom_text(aes(label=Text, group = Facto), position = dodger, col='red')+
        theme_minimal()
      
      
    }

I get what I want, but I lose the ability to assign this variable within my function. Is there way I can assign the "group=" dynamically within my function call, just as I'm doing with the "fill=" argument?

Upvotes: 0

Views: 1351

Answers (1)

Jon Spring
Jon Spring

Reputation: 66870

Does this do what you want?

MyBarPlot<-function(Data, ColName){
  dodger = position_dodge(width = 0.9)
  ggplot(Data, aes(x=XX, y=YY, fill= {{ColName}}))+
    geom_bar(stat="identity", color="black",position=position_dodge())+
    viridis::scale_fill_viridis(discrete = TRUE,option = "D",name=)+
    geom_text(aes(label=Text), position = dodger, col='red')+
    theme_minimal()
}


MyBarPlot(MyData,Facto)

enter image description here

Upvotes: 2

Related Questions