Adding text labels to ggplot2 Bar Chart

[This article was first published on Methods – finnstats, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Adding text labels to ggplot2, Is it possible to add text labels to a bar chart in a simple way?

Yes, In this article, you’ll learn how to add a frequency count to each bar in a bar chart.

First, let’s make a data frame.

Animated Graph GIF with gganimate & ggplot »

Adding text labels to ggplot2

set.seed(123)
data <- data.frame(x = sample(LETTERS[1:6], 300, replace = TRUE))
head(data)         
  x
1 C
2 F
3 C
4 B
5 B
6 F                                    
dim(data)
[1] 300   1

There is only one variable in the data frame, and it has 300 values. Let’s get the library loaded.

library("ggplot2")

Approach 1

Add the function geom text() to your graph. It necessitates the creation of mapping for x, y, and the text itself.

It is possible to move the text above or below the tops of the bars by setting vjust (vertical justification).

Adding labels to a bar graph of counts rather than values is a common case.

ggplot(data, aes(x = factor(x), fill = factor(x))) +
  geom_bar() +
  geom_text(aes(label = ..count..), stat = "count", vjust = 1.5, colour = "white")

Approach 2

Another option is to summarise the data frame using the table function in R, which is a straightforward process.

Visualization Graphs-ggside with ggplot »

data1<- as.data.frame(table(data$x))      
data1
   Var1 Freq
1    A   56
2    B   52
3    C   43
4    D   39
5    E   58
6    F   52

Now the data set is ready for visualization.

ggplot(data1, aes(x = Var1, y = Freq, fill = Var1)) + 
  geom_bar(stat = "identity") +
  geom_text(aes(label = Freq), vjust = 0)

Dot Plots in R-Strip Charts for Small Sample Size » finnstats

Subscribe to the Newsletter and COMMENT below!

The post Adding text labels to ggplot2 Bar Chart appeared first on finnstats.

To leave a comment for the author, please follow the link and comment on their blog: Methods – finnstats.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)