Plot table objects with ggplot?

2020-06-12 04:10发布

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?

标签: r plot ggplot2
2条回答
小情绪 Triste *
2楼-- · 2020-06-12 04:39

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.

查看更多
虎瘦雄心在
3楼-- · 2020-06-12 04:57

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.

查看更多
登录 后发表回答