How to Draw Counts on Top Each Bar of ggplot2 Barchart in R (Example Code)

In this R tutorial you’ll learn how to add the frequency count on the top of each bar of a ggplot2 barchart.

Setting up the Example

data(mtcars)                                              # Load and inspect data
table(mtcars$cyl)
#  4  6  8 
# 11  7 14
install.packages("ggplot2")                                 # Install & load ggplot2
library("ggplot2")

Example: Plotting Barchart with Values of Each Bar

data_cyl <- as.data.frame(table(mtcars$cyl))              # Summarizing cyl variable
data_cyl                                                  # Check summarized data
#   Var1 Freq
# 1    4   11
# 2    6    7
# 3    8   14
ggplot(data_cyl, aes(x = Var1, y = Freq, fill = Var1)) +  # Draw cyl with values on top
  geom_bar(stat = "identity") +
  geom_text(aes(label = Freq), vjust = 0)

r graph figure 1 how draw counts on top each bar ggplot2 barchart r

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top