How can I add a table to a graph?
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:
I can do thi开发者_C百科s 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?
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)
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.
精彩评论