更改ggplot对象的数据集 [英] Changing the dataset of a ggplot object

查看:106
本文介绍了更改ggplot对象的数据集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用ggplot2绘制数据的子集,我想知道我是否会以某种方式在原始数据的子集中使用ggplot对象中已经包含的所有选项.举个例子,这是第一个情节(代码块1):

I'm ploting subsets of my data with ggplot2 and I was wondering if I would somehow use all the options already contained in a ggplot object in a subset of the original data. As an example, take this is first plot (code chunk 1):

require(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt, color=factor(cyl))) + geom_point(shape=21, size=4)
print(p)

现在我想用mtcars的子集进行第二次绘图,所以我通常会这样做(代码块2):

Now I want to make a second plot with a subset of mtcars, so I would normally do this (code chunk 2):

new_data <- subset(mtcars, disp > 200)
p <- ggplot(new_data, aes(mpg, wt, color=factor(cyl))) + geom_point(shape=19, size=4)
print(p)

由于数据集中的微小差异,再次编写所有代码似乎有点麻烦.通常在ggplot中,您可以更改一些参数(这是正确的术语吗?),用p进行正确的操作.例如,我可以使用p + scale_color_manual(values=rainbow(3))更改绘图颜色.当然,这只是一个愚蠢的例子,但是当我有一个非常详细的情节时,它变得非常累人,到处都有许多调整.

It seems a little cumbersome to write all the code again for such a small difference in the dataset. Usually in ggplot you can change some parameters (is that the right term?) making the right operations with the p; for example, i can change the plot colors with p + scale_color_manual(values=rainbow(3)). Of course, this is just a silly example, but it gets really tiresome when I have a really detailed plot, with many tweaks everywhere.

所以基本上,我想知道的是是否有某种方法,例如函数x这样我可以做到这一点:

So basically, what I would like to know is if there is some way, like a function x such that I can do this:

p + x(data = new_data)

并与代码块2相同.

非常感谢, 胡安

推荐答案

我认为使用ggplot%+%运算符可以很容易地做到这一点.

I think it can be done very easily with the ggplot %+% operator.

p <- ggplot(mtcars, aes(mpg, wt, color=factor(cyl))) + geom_point(shape=21, size=4)
print(p)

p2<-p %+% mtcars[mtcars$disp>200,]
print(p2)

这篇关于更改ggplot对象的数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆