2013-07-30 84 views
2

我在R中有一些数据,我想将其表示为直方图(实际上,我将有6个直方图),然后将这些图导出到Excel文件中。我刚刚使用hist()函数,但我也在尝试使用ggplot2函数。每个直方图都有10,000条数据,所以我不能只导出原始数据并在Excel中创建直方图(我假设这会导致一个可笑的大小的Excel文件,这是我不想要的)。将直方图从R导出到Excel

有什么办法可以导出我的图?

+5

请参阅'?png'和'?ggsave'。如果你真的需要Excel(为什么要这么做?),请将PNG(或您选择的任何格式)导入到Excel中。 – Roland

+1

@Roland把它写成答案。我认为我们许多人会同意出口和进口是这类问题的答案。 – Dinre

+0

有没有一种方法可以让r代码将.png导入到excel中? – Chris

回答

3

excel.link包是RDCOMClient的包装。

以下示例仅适用于R 3.0.1中正常的RGUI(不是RStudio)。

# load package 
require(excel.link) 

# plot something 
plot(cos) 

# save graph to tmp file 
cos.plot=current.graphics() 

# add excel workbook 
xl.workbook.add() 

# add sheet to excel workbook 
xl.sheet.add() 

# put your graph starting at the top left in cell A1 
xl[a1]=list("Cosine plotting",cos.plot,"End of cosine plotting") 
1

另一个解决方案是离散化的数据存储到数据帧和导出的数据帧经由未CSV文件或任何其他格式到Excel。

> x <- rnorm(1000) 
> h <- hist(x) 
> h 
$breaks 
[1] -3.5 -3.0 -2.5 -2.0 -1.5 -1.0 -0.5 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 

$counts 
[1] 1 5 23 38 104 154 208 191 130 85 39 17 4 0 1 

$density 
[1] 0.002 0.010 0.046 0.076 0.208 0.308 0.416 0.382 0.260 0.170 0.078 0.034 0.008 0.000 0.002 

$mids 
[1] -3.25 -2.75 -2.25 -1.75 -1.25 -0.75 -0.25 0.25 0.75 1.25 1.75 2.25 2.75 3.25 3.75 

$xname 
[1] "x" 

$equidist 
[1] TRUE 

attr(,"class") 
[1] "histogram" 
> out <- data.frame(mid = h$mids, counts = h$counts) 
> write.table(out, file = "export.csv", row.names = FALSE, sep = ",") 

请注意,如果需要,也可以导出密度。