将打印功能的输出添加到 ggplot 图表 - r

Adding output of print function to ggplot chart - r

假设我有一个数据框:

df <- data.frame(x=1:10, y=4:13)
p <- ggplot(df,aes(x,y)) + geom_point()    

现在我想向这张图中添加很多东西,所以我使用了一个大的粘贴函数并打印输出。举个例子,假设我想在 x 轴标签内添加单词 'bananas'。

x <- "bananas"    
print(paste0("+ xlab('Price of", x[1], "')"), quote=F)

如果我尝试:

p + print(paste0("+ xlab('Price of", x[1], "')"), quote=F)

那显然不行。但是有没有办法将此函数的输出添加到 ggplot 对象 'p' 而无需来自控制台的 cutting/pasting?

即所以我们可以自动执行:

p + xlab('Price ofbananas')

如果要添加 Price of bananas 作为 x 标签,则:

p + xlab(paste0("Price of ", x[1]))

请记住您要添加 xlab,因此这应该是您的外部函数。在里面,你 add/create 你想要的标签。无需打印。

更新:

我想你想要的是eval(parse(text=xxx))。例如:

add <- paste0("xlab('Price of ", x[1], "')")
p + eval(parse(text=add))

请注意,我从文本中删除了 +,因为您需要在 p 旁边使用它来连接 eval

我不确定你为什么要这样做,但它确实有效。