1

I am trying to create a barplot with the ggplot2 library. My data is stored in read.csv2 format.

# Library
library(ggplot2)
library(tidyverse) # function "%>%"

# 1. Read data (comma separated)
data = read.csv2(text = "Age;Frequency
0 - 10;1
11 - 20;5
21 - 30;20
31 - 40;13
41 - 49;1")

# 2. Print table
df <- as.data.frame(data)
df

# 3. Plot bar chart
ggplot(df, aes(x = Age)) + 
  geom_bar() + 
  theme_classic()

The code runs fine, but it produces a graph that looks like all data are at max all the time.

enter image description here

2 Answers 2

3

You need to specify your y axis as well:

ggplot(df, aes(x = Age, y = Frequency)) + 
        geom_bar(stat = "identity") + 
        theme_classic()

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

The default value of geom_bar plots the frequency of the values which is 1 for all the Age values here (Check table(df$Age)). You may use geom_bar with stat = 'identity'

library(ggplot2)

ggplot(df, aes(Age, Frequency)) + 
  geom_bar(stat = 'identity') + 
  theme_classic()

OR geom_col :

ggplot(df, aes(Age, Frequency)) + 
  geom_col() + 
  theme_classic()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.