这实际上是两个问题之一 - 要么:
1) 如何存储 print() 调用的结果 [即x <- print(something)
] 不发送任何内容到当前图形输出?
-或-
2) ggplot 中是否有一个函数或方法可以存储对变量的plot() 调用而不调用 plot()
直接地? ggplotGrob
大概是这样,但是 ggplotGrob
对象不返回 $data
的列表其方式与存储 print()
的结果时得到的结果相同到一个变量。
我使用的技术来自 this所以答案是提取 geom_密度曲线的点,然后使用该数据生成一些注释。我在下面概述了这个问题——当我将其作为函数调用时,我在 pdf 中得到不需要的中间绘图对象以及最终绘图。我们的目标是摆脱那个不受欢迎的情节;鉴于该基地hist()
有一个plot = FALSE
我希望对 R 视口(viewport)有更多了解的人能够修复我的 plot()
调用(解决方案#1),但坦率地说,任何解决方案都可以。
library(ggplot2)
library(plyr)
demo <- function (df) {
p <- ggplot(
df
,aes(
x = rating
)
) +
geom_density()
#plot the object so we can access $data
render_plot <- plot(p + ggtitle("Don't want this plot"))
#grab just the DF for the density line
density_df <- render_plot$data[[1]]
#get the maximum density value
max_y <- ddply(density_df, "group", summarise, y = max(y))
#join that back to the data to find the matching row
anno <- join(density_df, max_y, type = 'inner')
#use this to annotate
p <- p + annotate(
geom = 'text'
,x = anno$x
,y = anno$y
,label = round(anno$density, 3)
) +
ggtitle('Keep this plot')
return(p)
}
#call to demo outputs an undesired plot to the graphics device
ex <- demo(movies[movies$Comedy ==1,])
plot(ex)
#this is problematic if you are trying to make a PDF
#a distinct name for the pdf to avoid filesystem issues
unq_name <- as.character(format(Sys.time(), "%X"))
unq_name <- gsub(':', '', unq_name)
pdf(paste(unq_name , '.pdf', sep=''))
p <- demo(movies[movies$Drama ==1,])
print(p)
dev.off()
最佳答案
使用ggplot_build
:
render_plot <- ggplot_build(p + ggtitle("Don't want this plot"))
关于r - 将plot()调用的结果存储到变量而不发送到当前图形设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17577352/