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
510 views
in Technique[技术] by (71.8m points)

r - Variable hline in ggplot with facet

Using the Iris data set as an example, I can produce a ggplot with facet. ggplot with facet The code is:

library(ggplot2)
data(iris)
y=iris
y$Petal.Width.Range=factor(ifelse(y$Petal.Width<1.3,"Narrow","Wide"))
y$Petal.Length.Range=factor(ifelse(y$Petal.Length<4.35,"Short","Long"))
ggplot(y, aes(Sepal.Length,Sepal.Width)) + 
  geom_point(alpha=0.5)+
  geom_hline(yintercept =3 ,alpha=0.3)+
  facet_grid(Petal.Width.Range ~ Petal.Length.Range)

Here I have a horizontal spec of 3 in each of the 4 cases. What should I do if I want a case dependent spec please? For example, I can define 4 different specs as the following:

y$threshold=2
y$threshold[(y$Petal.Width.Range=="Narrow")&(y$Petal.Length.Range=="Short")] =2
y$threshold[(y$Petal.Width.Range=="Narrow")&(y$Petal.Length.Range=="Long")] =2.5
y$threshold[(y$Petal.Width.Range=="Wide")&(y$Petal.Length.Range=="Short")] =3.1
y$threshold[(y$Petal.Width.Range=="Wide")&(y$Petal.Length.Range=="Long")] =4

How should I add y$threshold into the ggplot commands please?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

One easy solution is just to change your hline call to this: geom_hline(aes(yintercept=threshold), alpha=0.3) +.

The problem is, that would draw 150 lines on your plot (150 being the number of rows in the y data.frame). Maybe that's ok with you, because the lines would mostly be stacked on top of each other and you would really only see four lines, in their correct locations.

However, here is another solution where I create a smaller auxiliary data.frame. This is a common approach in ggplot2. Notice how the new data.frame is specified as the data source inside the geom_hline call.

hline_dat = data.frame(Petal.Width.Range=c("Narrow", "Narrow", "Wide", "Wide"),
                       Petal.Length.Range=c("Short", "Long", "Short", "Long"),
                       threshold=c(2, 2.5, 3.1, 4))

p = ggplot(y, aes(Sepal.Length,Sepal.Width)) + 
    geom_point(alpha=0.5) +
    geom_hline(data=hline_dat, aes(yintercept=threshold), colour="salmon") +
    facet_grid(Petal.Width.Range ~ Petal.Length.Range)

ggsave("plot.png", plot=p, height=4, width=6)

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

...