R Modify Position of geom_text Labels on Dodged Barplot (Example Code)
In this article, I’ll illustrate how to properly add text labels to a dodged ggplot2 barchart in R.
Setting up the Example
data(iris) # Load and modify example data iris_new <- iris[c(1:2, 51:52, 101:102), c(1, 5)] iris_new$subgroup <- LETTERS[1:2] iris_new # Display example data # Sepal.Length Species subgroup # 1 5.1 setosa A # 2 4.9 setosa B # 51 7.0 versicolor A # 52 6.4 versicolor B # 101 6.3 virginica A # 102 5.8 virginica B |
data(iris) # Load and modify example data iris_new <- iris[c(1:2, 51:52, 101:102), c(1, 5)] iris_new$subgroup <- LETTERS[1:2] iris_new # Display example data # Sepal.Length Species subgroup # 1 5.1 setosa A # 2 4.9 setosa B # 51 7.0 versicolor A # 52 6.4 versicolor B # 101 6.3 virginica A # 102 5.8 virginica B
install.packages("ggplot2") # Install ggplot2 package library("ggplot2") # Load ggplot2 package |
install.packages("ggplot2") # Install ggplot2 package library("ggplot2") # Load ggplot2 package
ggplot(iris_new, # Labels at wrong location aes(x = Species, y = Sepal.Length, fill = subgroup)) + geom_bar(stat = "identity", position = "dodge") + geom_text(aes(Species, label = Sepal.Length)) |
ggplot(iris_new, # Labels at wrong location aes(x = Species, y = Sepal.Length, fill = subgroup)) + geom_bar(stat = "identity", position = "dodge") + geom_text(aes(Species, label = Sepal.Length))
Example: How to Position geom_text Labels on a Dodged Barchart
ggplot(iris_new, # Modifying position of labels aes(x = Species, y = Sepal.Length, fill = subgroup)) + geom_bar(stat = "identity", position = "dodge") + geom_text(aes(Species, label = Sepal.Length), position = position_dodge(width = 1)) # Using position_dodge |
ggplot(iris_new, # Modifying position of labels aes(x = Species, y = Sepal.Length, fill = subgroup)) + geom_bar(stat = "identity", position = "dodge") + geom_text(aes(Species, label = Sepal.Length), position = position_dodge(width = 1)) # Using position_dodge
Further Resources & Related Tutorials
Below, you may find some further resources that are similar to the content of this article.