PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, June 28, 2022

[FIXED] How do I make a bar graph with labels and counts?

 June 28, 2022     ggplot2, graph, r     No comments   

Issue

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”)

Solution

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().



Answered By - jpiversen
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing