0
votes

I'm working on the Titanic dataset from R. I want to analyse the dataset using a ggplot (stacked and group bar plots). So I wanted to convert the table into a data-frame so I could plot the graphs. I used the following code to convert :

df<-as.data.frame(Titanic)
View(df)

However, even on viewing I see my df to be more like a data-table. And further when I tried to use it to plot a function usinf the code:

ggplot(data=df) + geom_bar(aes(x=Class,y=Sex))

All it shows is an empty plot, with just the labels on x and y axis, along with the categorical values of Sex as Male & Female and Class as 1st,2nd,3rd and crew. What confuses me even more is that it's picking up the categorical values from the dataset but not the observations.

Please let me know how I can convert to dataframe correctly. Thanks :)

1

1 Answers

0
votes

If I reproduce your code it gives me this error:

Error : Mapping a variable to y and also using stat="bin".

This is because you also included the y=Sex in your script. The main question therefore is, what would you like to plot?

If this is a barchart with the count of persons in each class the code will be:

ggplot(data=df) + geom_bar(aes(x=Class))

If it will be the total amount of females/males it will be:

ggplot(data=df) + geom_bar(aes(x=Sex))

Do not try to plot them at the same time.

To get back to the question. There is nothing wrong with your data frame. It is your ggplot code that is faulty.