Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot table objects with ggplot?

Tags:

plot

r

ggplot2

I've got this data:

         No    Yes
Female  411   130
Male    435   124

which was created using the standard table command. Now with plot I can plot this as such:

plot(table(df$gender, df$fraud))

and it then outputs a 2x2 bar chart.

So my question is, how can I do this with ggplot2? Is there any way with out transforming the table-object to a data frame? I would do that, but it becomes a mess and you then need to rename column and row headers and it just becomes a mess for what is really a quite simple thing?

like image 775
user3720596 Avatar asked Nov 06 '14 19:11

user3720596


2 Answers

Something such as

ggplot(as.data.frame(table(df)), aes(x=gender, y = Freq, fill=fraud)) + 
    geom_bar(stat="identity")

gets a similar chart with a minimum amount of relabelling.

like image 67
WaltS Avatar answered Oct 20 '22 00:10

WaltS


ggplot2 works with data frame, so, you have to convert table into a frame. Here is a sample code:

myTable <- table(df$gender, df$fraud)
myFrame <- as.data.frame(table(myTable))

Now, you can use myFrame in ggplot2:

ggplot(myFrame, aes(x=gender))+
  geom_bar(y = Freq)

see Coerce to a Data Frame for more information.

like image 20
Mostafa Avatar answered Oct 20 '22 02:10

Mostafa