Home > Net >  How do I make a bar graph with labels and counts?
How do I make a bar graph with labels and counts?

Time:12-30

I realize this is a simple question, but I’m having trouble getting this graph to display right.

I have a dataset like:

pet pet_counts
dog 22
cat 100
birs 2

I want to make a bar graph that has the X-Axis labeled with each animal and the counts along the Y. When I specify, labs it just changed the words in the label but not the value below the tick marks.

I want the x axis to say dog and then in the Y have a count for f 22, for example.

I have tried:

Graph <- ggplot(data = animals, aes(pet_counts))   geom_bar(stat=“count”)   labs(x = “pet”)

CodePudding user response:

I think you're looking for geom_col() instead of geom_bar():

library(dplyr)
library(ggplot2)

animals <- tibble(
  pet = c("dog", "cat", "birds"),
  pet_counts = c(22, 100, 2)
)

animals %>% 
  ggplot(aes(x = pet, y = pet_counts))   
  geom_col()  
  labs(
    x = "Pet",
    y = "Count"
  )

The labs() function is optional, and will just change the names on the axis to something more readable.

The result:

Final plot

The difference between geom_col() and geom_bar(), according to the documentation:

geom_bar() makes the height of the bar proportional to the number of cases in each group. If you want the heights of the bars to represent values in the data, use geom_col() instead.

Since you already have pet_counts, you should use geom_col().

  • Related