Rui
Rui

Reputation: 317

Changing line color in ggplot based on "several factors" slope

UPDATED: I have the following data which I would like to draw a line between the groups, based on the slope of 3 factors `("I","II","III").

set.seed(205)
dat = data.frame(t=rep(c("I","II","III"), each=10), 
             pairs=rep(1:10,3), 
             value=rnorm(30), 
             group=rep(c("A","B"), 15))

I have tried the following, but I cannot manage to connect change the color of the line connecting "I" - "III" and "II" - "III":

ggplot(dat %>% group_by(pairs) %>%
     mutate(slope = (value[t=="II"] - value[t=="I"])/( value[t=="II"])- value[t=="I"]),
   aes(t, value, group=pairs, linetype=group, colour=slope > 0)) +
geom_point() +
geom_line()

This is a very similar issue to Changing line color in ggplot based on slope

I hope I was able to explain my problem.

Upvotes: 0

Views: 618

Answers (1)

bouncyball
bouncyball

Reputation: 10761

We can split apart the data, and get what you want:

#calculate slopes for I and II
dat %>% 
    filter(t != "III") %>%
    group_by(pairs) %>%
    # use diff to calculate slope
    mutate(slope = diff(value)) -> dat12

#calculate slopes for II and III
dat %>% 
    filter(t != "I") %>%
    group_by(pairs) %>%
    # use diff to calculate slope
    mutate(slope = diff(value)) -> dat23

ggplot()+
    geom_line(data = dat12, aes(x = t, y = value, group = pairs, colour = slope > 0,
                                linetype = group))+
    geom_line(data = dat23, aes(x = t, y = value, group = pairs, colour = slope > 0,
                                linetype = group))+
    theme_bw()

enter image description here

Since the data in dat came sorted by t, I used diff to calculate the slope.

Upvotes: 1

Related Questions