Using ggplot2 to create a bar chart

So I'm trying to create a simple bar chart of Survive vs Not Survive for the common Titanic data set in R. I keep getting just the number of No's and Yes's, and not the frequencies or counts associated with each no and yes. This is obviously not what is wanted. I am trying to just practice with ggplot2 and make some graphs. What am I doing wrong here?

The Bad Barchart:

#install.packages(tidyverse)
#install.packages(titanic)

library(tidyverse)
library(titanic)

view(Titanic)

titanic - as.data.frame(Titanic)

titanic$Survived - as.factor(titanic$Survived)

ggplot(titanic, aes(Survived, fill = Survived))+
  geom_bar()+
  ggtitle(Barplot to represent Passenger Count who Survived vs who Died)

Topic ggplot2 data visualization r

Category Data Science


The number of people in each category is not defined by the number of rows but by the number in the Freq column. You therefore have to take the sum of those values and plot the result, this can be done by supplying the column which holds the value you want to use on the y-axis to aes() and use stat="identity" for geom_bar:

library(tidyverse)
library(titanic)

titanic <- as.data.frame(Titanic)
titanic$Survived <- as.factor(titanic$Survived)

ggplot(titanic, aes(Survived, Freq, fill = Survived))+
  geom_bar(stat="identity")+
  ggtitle("Barplot to represent Passenger Count who Survived vs who Died")

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.