Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable hline in ggplot with facet

Tags:

r

ggplot2

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?

like image 223
Nicholaev Avatar asked Feb 06 '23 19:02

Nicholaev


1 Answers

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

like image 185
bdemarest Avatar answered Feb 08 '23 11:02

bdemarest