Search code examples
rggplot2bar-charttextlabel

How to alter ggplot2 text labels that are based off of legend values


I'm trying to create a stacked bar chart that uses the values in 'MaskID' to create text labels. Each unique value in 'MaskID' will have its own color and I want the names of the values to be with their corresponding colors on the bar plot.

p <- ggplot(df, aes(x, y))
p <- p + xlab("xlabel")
p <- p + ylab("ylabel")
p <- p + ggtitle("ylabel vs xlabel")
p <- p + geom_bar(stat="identity", aes(fill=MaskID))
p <- p + geom_text(aes(label=MaskID))

I also don't want the names to show if the bar value is 0. The 'MaskID' names are all clustered together where the bar values are 0. Does anyone know how to customize this? I'm still quite new to ggplot2 (and R).


Solution

  • Try this

    p + geom_text(aes(label= ifelse(y != 0, as.character(MaskID), '')))