Home > Enterprise >  Add custom text to ggplot when x axis is categorical
Add custom text to ggplot when x axis is categorical

Time:10-25

I was trying to add custom text to my ggplot where x-axis is categorical. Below is my code

library(ggplot2)
data = rbind(data.frame('val' = c(10, 30, 15), 'name' = c('A', 'B', 'C'), group = 'gr1'), data.frame('val' = c(30, 40, 12), 'name' = c('A', 'B', 'C'), group = 'gr2'), data.frame('val' = c(10, 30, 15), 'name' = c('A', 'B', 'C'), group = 'gr3'))

ggplot(data,                        
       aes(x = group,
           y = val,
           fill = name))  
    geom_bar(stat = "identity",
             position = "stack", width = .1)  
    geom_text(data = data.frame('group' = c('gr1', 'gr2', 'gr3'), 'label' = c('X', 'Y', 'Z')), mapping = aes(x = group, y = 40, label = label))

Above implementation is failing with error

Error in FUN(X[[i]], ...) : object 'name' not found

Could you please help me to correct this error?

Many thanks for your help.

CodePudding user response:

The issue is that you specified fill=name as a global aesthetic but the dataframe passed to geom_text does not contain a column called name. To fix that make fill=name a local aes of geom_col or add inherit=FALSE to geom_text:

library(ggplot2)

ggplot(data,                        
       aes(x = group,
           y = val))  
  geom_col(aes(fill = name), width = .1)  
  geom_text(data = data.frame('group' = c('gr1', 'gr2', 'gr3'), 'label' = c('X', 'Y', 'Z')), mapping = aes(x = group, y = 40, label = label))

  • Related