将 ipython 笔记本中的 ggplot 输出保存到文件

Save output of ggplot in ipython notebook to file

我想在 ipython 笔记本中使用 ggplot。我使用 rmagic 将数组传入 R 并可以将其绘制到输出单元格。但是,将绘图保存到文件似乎不起作用。

%load_ext rpy2.ipython

新建单元格。我的python数据叫做data.

%%R -i data
library(ggplot2)

df=data.frame(x=seq(1,length(data)),y=data)
pdf('plot.pdf')
ggplot(data=df, aes(x=x,y=y)) + geom_point()
dev.off()

当我单击文件 plot.pdf 时出现错误 'File cannot be opened. It may be damaged or use a file format that Preview doesn’t recognize.'

试试这个:

df <- data.frame(x=seq(1,length(data)),y=data)
ggplot(data=df, aes(x=x,y=y)) + geom_point()
ggsave('plot.pdf', width=8.27, height= 11.69) #A4 size in inches
dev.off()

如果打开特定设备(此处为 PDF 文件),您将必须调用 print(就像您在非交互式 R 中使用该代码一样)。

df=data.frame(x=seq(1,length(data)),y=data)
pdf('plot.pdf')
p <- ggplot(data=df, aes(x=x,y=y)) + geom_point()
print(p)
dev.off()

这可能比调用 ggsave 更明确,后者似乎在有多个绘图时猜测应该绘制什么。