我试图在一个数据集的2个不同的方面产生2个不同的geom_vlines与不同的颜色。我这样做是为了突出两个不同方面的意义。
下面是数据集:
Pclass Sex Age SibSp Parch Fare Cabin Embarked Survived
3 male 22 1 0 7.25 S 0
1 female 38 1 0 71.2833 C85 C 1
3 female 26 0 0 7.925 S 1
1 female 35 1 0 53.1 C123 S 1
3 male 35 0 0 8.05 S 0
1 male 54 0 0 51.8625 E46 S 0代码如下:
g<-ggplot(data = train3, aes(x = Age, y = Survived, colour = factor(Pclass)))
g<-g+facet_wrap(~Sex)
g<-g+geom_point(size = 4, alpha = 0.2)+ggtitle("Survival by Gender")+theme(plot.title = element_text(hjust = 0.5))
g<-g+geom_vline(data = subset(train3,Sex=="female"), xintercept = mean(train3[which(train3$Sex=="female"),3]), colour = "pink", size = 1)
g<-g+geom_vline(data = subset(train3,Sex=="male"), xintercept = mean(train3[which(train3$Sex=="male"),3]), colour = "blue", size = 1)
g下面是输出

我实际上只想在每个方面产生一条vline :粉红色的女性和蓝色的男性。
给here的建议也不起作用。显示的错误为:
Error in .(Sex == "female") : could not find function "."发布于 2017-05-26 16:48:08
您可以创建一个data.frame,其中一列是用于行的截取值,第二列是用于Sex的列。因此,在使用facet_wrap时,它们是分开的。
类似于:
dataInt <- train3 %>%
group_by(Sex) %>%
summarize(Int = mean(Age))然后,您可以在脚本中使用它:
g<-ggplot(data = train3, aes(x = Age, y = Survived, colour = factor(Pclass))) +
facet_wrap(~Sex) +
geom_vline(data=dataInt, aes(xintercept=Int))没有你的数据,我不能测试这个。
编辑:对于reprex,如果我使用与Adam Quek相同的数据作为可重现的示例,代码将自动执行,如下所示:
library(tidyverse)
dataLine <- iris %>%
group_by(Species) %>%
summarize(mean_x = mean(Sepal.Length))
ggplot(iris) +
aes(x = Sepal.Length, y = Petal.Length) +
facet_wrap(facets = vars(Species)) +
geom_point() +
geom_vline(data = dataLine, aes(xintercept = mean_x, colour = Species))

https://stackoverflow.com/questions/44196384
复制相似问题