Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

ggplot2 - How to produce different geom_vline in different facets in R?

I am trying to produce 2 different geom_vlines with different colours in 2 different facets of a dataset. I am doing this to highlight means of 2 different facets.

Here's the dataset:

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

Here's the code:

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

Here's the output

enter image description here

I actually want to produce only 1 vline in each facet: pink in female and blue in male.

The suggestion give here is not working either . Error shown being:

Error in .(Sex == "female") : could not find function "."
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's how you can put in different geom_vline for different iris species:

ggplot(iris, aes(Sepal.Length, Petal.Length)) + facet_wrap(~Species, scales="free") + geom_point() + 
  geom_vline(data=filter(iris, Species=="setosa"), aes(xintercept=5), colour="pink") + 
  geom_vline(data=filter(iris, Species=="versicolor"), aes(xintercept=6), colour="blue") + 
  geom_hline(data=filter(iris, Species=="virginica"), aes(yintercept=6), colour="green") 

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...