ggplot:只有满足某些标准才能绘制图层 [英] ggplot: plotting layers only if certain criteria are met
问题描述
在 ggplot
本身内是否有过滤的方法?也就是说,我想这样做
Is there a method of filtering within ggplot
itself? That is, say I want to do this
p <- ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, species)) +
geom_point(size = 4, shape = 4) +
geom_point(size = 1, shape = 5 # do this only for data that meets some condition. E.g. Species == "setosa")
我知道有些窍门可以用来设置size = 0 if Species!=setosa
或者重置数据如下所示,但这里有所有黑客行为。
I know there are hacks I can use like setting the size = 0 if Species != "setosa"
or resetting the data like shown below, but there's all hacks.
p <- ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, species)) +
geom_point(size = 4, shape = 4) +
geom_point(data = iris %>% filter(Species == "setosa"), colour = "red") +
geom_point(data = iris %>% filter(Species == "versicolor"), shape = 5)
基本上,我有一张图表,只有在某些标准现在,我正在使用上面的黑客来完成这个任务d它在晚上让我保持沉默,我的灵魂从我创造的混乱中慢慢死去。不用说,任何帮助将非常感谢!
Basically, i have a chart where certain things should be displayed only if a certain criteria is met, and right now, I'm using the hack above to accomplish this and it's keeping me up at night, my soul slowly dying from the mess I've created. Needless to say, any help would be very much appreciated!
编辑
恐怕我的例子可能太简单了。基本上,给定 ggplot(data = ...)
,如何添加这些图层,全部使用绑定到ggplot obj的数据:
I'm afraid my example may have been too simplistic. Basically, given ggplot(data = ...)
, how do I add these layers, all using the data bound to the ggplot obj:
- 绘制曲线
- 绘制满足标准#1的点上的点。这些点会变成红色。不符合标准的点不会得到一个点(不是像点大小设置为零,或alpha设置为0)。
- 将标签添加到满足条件的点#2。
Critera #1 and #2 could be anything. E.g. label only outlier points. Draw in red only those points which are outside a specific range, etc.
I 不要想
- 绑定一个新的数据集ala
ggplot(data = subset(iris,Species ==setosa),...)
或ggplot(data = filter(iris,Species ==setosa)
。 - 使用缩放hack例如,如果我有1000个点,并且只有1个点符合给定条件,我希望它只将它的绘图逻辑应用到那个点上点而不是看,并且造型所有1000点
推荐答案
显然,图层现在接受函数作为数据参数,所以你可以使用它
apparently layers now accept a function as data argument, so you could use that
pick <- function(condition){
function(d) d %>% filter_(condition)
}
ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length, species)) +
geom_point(size = 4, shape = 4) +
geom_point(data = pick(~Species == "setosa"), colour = "red") +
geom_point(data = pick(~Species == "versicolor"), shape = 5)
这篇关于ggplot:只有满足某些标准才能绘制图层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!