r - 将plot()调用的结果存储到变量而不发送到当前图形设备

标签 r pdf ggplot2

这实际上是两个问题之一 - 要么:

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/

相关文章:

r - 在 R 看门人包中使用 `make_clean_names` 保留重复项

r - 如何平滑R ggplot中的线条

php - 在 PHP 中拼合 PDF?

node.js - 试图在使用 Puppeteer 生成的 PDF 上隐藏第一个页脚/页眉

html - ipython笔记本在开始新段落时转换为带有缩进的pdf

r - 使用 ggplot2 的累积图

r - 将带有火星和金星符号的 R 图另存为 pdf

r - 在 R 中,如何通过来自另一个 data.frame 的值对 data.frame 进行子集?

R - 在使用注释时向 ggmap (ggplot2) 添加图例

r - 在 ggplot2 函数中访问轴标签的变量属性信息