在R图形的图例中包含小表 [英] Include small table in legend in R graphics

查看:88
本文介绍了在R图形的图例中包含小表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在绘制按国家/地区分组的公司的销售点图.所以我的代码是dotchart(sales, labels=company, groups=country, data=mydata).我还创建了一个按国家/地区划分的平均销售额的表格.有什么办法可以将此表作为点图内的图例包括在内?

I am plotting a dotplot for sales for companies grouped by countries. So my code is dotchart(sales, labels=company, groups=country, data=mydata). I have also created a table of mean sales values by country. Is there any way to include this table as legend inside the dotplot?

四个小时后……我偶然发现了一种非常巧妙的方法,可以使用plotrix包中的addtable2plot命令将表格信息添加到绘图中.跟进chl的示例:

Four hours later... I just stumbled upon a really neat way of adding tabular information to plots using the addtable2plot command in the plotrix package. Following up on chl's example:

res <- matrix(nc=3, nr=4)
for (i in 1:4) res[i,] <- tapply(iris[,i], iris[,5], mean)
colnames(res) <- levels(iris[,5])
rownames(res) <- colnames(iris)[1:4]

library(plotrix)
dotchart(res, auto.key=list(position="top", column=3), xlab="Mean"); addtable2plot(3,15, res, cex=.8)

推荐答案

这是我的看法grid(和虹膜数据集):

Here is my take wiith grid (and the Iris dataset):

library(lattice)
library(grid)
library(gridExtra)
res <- matrix(nc=3, nr=4)
for (i in 1:4) res[i,] <- tapply(iris[,i], iris[,5], mean)
colnames(res) <- levels(iris[,5])
rownames(res) <- colnames(iris)[1:4]
dp <- dotplot(res, auto.key=list(position="top", column=3), xlab="Mean")

pdf("1.pdf", width=10, height=5)
grid.newpage() 
pushViewport(viewport(layout=grid.layout(1, 2, widths=unit(c(5,4), "inches"))))

pushViewport(viewport(layout.pos.col=1, layout.pos.row=1)) 
print(dp, newpage=FALSE) 
popViewport(1)

pushViewport(viewport(layout.pos.col=2, layout.pos.row=1, clip="on"))
grid.draw(tableGrob(head(iris), gp=gpar(fontsize=6, lwd=.5)))
popViewport()
dev.off()

Hadley Wickham的github页面上仅提供了另一个ggplot2解决方案,

Another solution with ggplot2 only is available on Hadley Wickham's github page, Mixing ggplot2 graphs with other graphical output. Finally, the on-line help page for gridExtra::grid.arrange() includes additional example.

要在图表中显示表格,我们可以修改代码,如下所示:

To show the Table inside the plot, we can modify the code as follows:

grid.newpage() 
pushViewport(viewport(layout=grid.layout(1, 1, widths=unit(c(5,4), "inches"))))

pushViewport(viewport(layout.pos.col=1, layout.pos.row=1)) 
print(dp, newpage=FALSE) 
popViewport(1)

pushViewport(viewport(x=0.5, y=0.3, clip="off"))
grid.draw(tableGrob(head(iris), padding.v=unit(1, "mm"), padding.h=unit(1, "mm"), 
          gp=gpar(fontsize=6, lwd=.5)))
popViewport()

产生

(调用tableGrob()时可以使用theme=更改单元格的背景颜色.)

(The background color of the cells can be changed using theme= when calling tableGrob().)

这篇关于在R图形的图例中包含小表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆