有色矩阵R节省乳胶

时间:2016-09-28 23:22:58

标签: r image matrix import latex

我在R

中有这个“有色”矩阵
library(gplots)

#Build the matrix data to look like a correlation matrix
x <- matrix(rnorm(64), nrow=8)
x <- (x - min(x))/(max(x) - min(x)) #Scale the data to be between 0 and 1
for (i in 1:8) x[i, i] <- 1.0 #Make the diagonal all 1's

#Format the data for the plot
xval <- formatC(x, format="f", digits=2)
pal <- colorRampPalette(c(rgb(0.96,0.96,1), rgb(0.1,0.1,0.9)), space = "rgb")

#Plot the matrix
x_hm <- heatmap.2(x, Rowv=FALSE, Colv=FALSE, dendrogram="none", main="8 X 8 Matrix Using Heatmap.2", xlab="Columns", ylab="Rows", col=pal, tracecol="#303030", trace="none", cellnote=xval, notecol="black", notecex=0.8, keysize = 1.5, margins=c(5, 5))

我想在Latex中导入它。我能怎么做? 谢谢你的帮助!

1 个答案:

答案 0 :(得分:2)

gplots::heatmap.2仅打印彩色矩阵的图像,实际上并不返回彩色矩阵。尽管如此,我们可以自己重新创建并将其转换为乳胶表(尽管保存图像并在乳胶中使用\includegraphics的注释也同样出色)。这是您可以使用的.Rmd文件。确保编织为PDF!

---
title: "Hey Stack"
header-includes:
   - \usepackage[table]{xcolor}
output: pdf_document
---

```{r, include = FALSE}
library(gplots)
library(xtable)

#Build the matrix data to look like a correlation matrix
x <- matrix(rnorm(64), nrow=8)
x <- (x - min(x))/(max(x) - min(x)) #Scale the data to be between 0 and 1
for (i in 1:8) x[i, i] <- 1.0 #Make the diagonal all 1's

#Format the data for the plot
xval <- formatC(x, format="f", digits=2)
pal <- colorRampPalette(c(rgb(0.96,0.96,1), rgb(0.1,0.1,0.9)), space = "rgb")

x_hm <- heatmap.2(x, Rowv=FALSE, Colv=FALSE, dendrogram="none", 
  main="8 X 8 Matrix Using Heatmap.2", xlab="Columns", ylab="Rows", col=pal,
  tracecol="#303030", trace="none", cellnote=xval, notecol="black", notecex=0.8, 
  keysize = 1.5, margins=c(5, 5))
```

```{r, results = 'asis'}
color_m <- apply(round(x, 2), 2, function(r) {
  col <- cut(r, x_hm$breaks, gsub("#", "", x_hm$col), include.lowest = TRUE) 

  paste0("\\cellcolor[HTML]{", col, "}{", r, "}")
})

print(xtable(color_m), sanitize.text.function = identity, comment = FALSE, 
      include.rownames = FALSE, include.colnames = FALSE)
```