ggplot2:从ggplot-Object创建一个独立的副本 [英] ggplot2: Create an independent copy from an ggplot-Object
问题描述
我不知道如何把这个放在OO-Speech中。但是当你创建一个ggplot时,它将依赖于源数据框架。那么如何在没有这种依赖的情况下保存一个ggplot?
dat < - data.frame(x = runif(10), y = runif(10))
g < - ggplot(dat,aes(x,y))+ geom_point()
g
dat < - NULL
g
第二个$ g $不会产生图形,因此dat是$ NULL $。我怎样才能保存$ g $,以便dat可以被更改?
我知道这不是一个好习惯,但我得到了一些我不想要的很长的代码我认为@约书亚的答案太复杂了(如果我明白你想要的是什么) )。我认为改变存储在plot对象中的数据帧是没有意义的,因为 ggplot2 有一个特殊的infix操作符,专门设计用于将新数据框应用于给定的plot对象:%+%
。
<$ p (x,y))+ b(< -gfp(dat,aes(x,y))+ geom_point()
g
#更改数据框
dat $ y <-rexp(10)
#Replot g使用改变的数据帧
g%+%dat
当然,这不仅适用于原始数据框的更改版本,而且适用于全新的数据框,前提是它包含所有必需的变量(并且它们的命名方式相同)。 b $ b
I'm not sure how to put this in OO-Speech. But when you are creating a ggplot it will be dependent from the source data.frame. So how can you save a ggplot without that dependency?
dat <- data.frame(x=runif(10),y=runif(10))
g <- ggplot(dat, aes(x,y)) + geom_point()
g
dat <- NULL
g
The second $g$ won't produce a plot hence dat is $NULL$. How can I save $g$ so that dat can be changed?
I know it is not good practice but I got some very long code on which I don't want to fiddle about.
Personally, I think that @Joshua's answer is too complicated (if I'm understanding what you want to do).
I don't think it makes any sense to change the data frame stored in the plot object, since ggplot2 has a special infix operator that is specifically designed to apply a new data frame to a given plot object: %+%
.
dat <- data.frame(x=runif(10),y=runif(10))
g <- ggplot(dat, aes(x,y)) + geom_point()
g
#Change the data frame
dat$y <- rexp(10)
#Replot g using the altered data frame
g %+% dat
This works, of course, with not just altered versions of the original data frame, but an entirely new data frame, provided it has all the required variables in it (and they are named the same).
这篇关于ggplot2:从ggplot-Object创建一个独立的副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!