How can I add a table to a graph?

2019-05-12 00:43发布

I have created a dodged bar chart using the following commands:

a = c(1,1,1,1,1,1,1,2,2,2,2,2,2,2) 
b = c("A","A","A","B","B","B","B","C","C","D","D","D","D","D") 
c = c(60,20,20,80,5,5,5,50,50,25,25,25,20,5) 
dat = data.frame(Group=a, Member=b, Percentage=c) 
ggplot(dat, aes(x=Member, y=Percentage)) + geom_bar(stat="identity", position="dodge", fill="white", colour="black") 

If I have a set of values:

table_values = c("2", "4", "2", "1")
table_total = c("A", "B", "C", "D")
tab = data.frame(Type=table_total, Value=table_values)

How can I add this as a table to my graph so that it is aligned? Something like this:

enter image description here

I can do this manually but I have a lot of graphs to generate so I was wondering if this can be automated. Any suggestions on how to do this?

1条回答
【Aperson】
2楼-- · 2019-05-12 01:11

It's a bit of a hack, but you can annotate with geom_text, placing the text as a slightly negative y value. This puts it into the plot area rather than below the axis.

ggplot(dat, aes(x=Member, y=Percentage)) + 
  geom_bar(stat="identity", position="dodge", fill="white", colour="black") +
  geom_text(aes(x=table_total, label=table_values), y=-2, data=tab)

Using geom_text to make something like a table in a graph

I more involved approach would be to create two separate plots, one that is the bar chart, one that is the "table" (turning off almost all the theme elements) and using something like align.plots (not sure if that is the right name) in the ggExtra package.

查看更多
登录 后发表回答