这实际上是两个问题之一 - 或者:
1)如何在不向当前图形输出发送任何内容的情况下存储print()调用[ie x <- print(something)]的结果?-要么-
2)ggplot中是否有一个函数或方法将一个plot()调用存储到一个变量而不plot()直接调用?ggplotGrob是在球场,但是ggplotGrob对象不会返回列表$data中的列表,就像将结果存储print()到变量时一样.
我正在使用从这个 SO答案中提取的技术来提取geom_density曲线的点,然后使用该数据生成一些注释.我已经概述了下面的问题 - 当我将其称为函数时,我在pdf中得到了不需要的中间绘图对象,以及最终的绘图.目标是摆脱那个不受欢迎的阴谋; 鉴于基地hist()有一个plot = FALSE选项,我希望知道更多关于R视口的人能够修复我的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()
Run Code Online (Sandbox Code Playgroud)
用途ggplot_build:
render_plot <- ggplot_build(p + ggtitle("Don't want this plot"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2349 次 |
| 最近记录: |