Europa
Europa

Reputation: 1292

Barplot with ggplot2 using data from read.csv2

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

Upvotes: 1

Views: 86

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389235

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

Upvotes: 1

bird
bird

Reputation: 3326

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

Upvotes: 3

Related Questions