Changing line color in ggplot based on slope

后端 未结 1 935
执笔经年
执笔经年 2020-12-11 11:32

I have the following code which plots points and draw a line between them.

ggplot (data = subset(df, vowel == \"O\" & gender == \"f\"), aes (x = time, y         


        
相关标签:
1条回答
  • 2020-12-11 12:13

    You haven't provided sample data, so here's a stylized example. The general idea is that you create a variable that tests whether the slope is greater than zero and then map that to a colour aesthetic. In this case, I use the dplyr chaining operator (%>%) in order to add the slope on the fly within the call to ggplot. (I went to the trouble of calculating the slope, but you could just as well test whether value[t==2] > value[t==1] instead.)

    library(dplyr)
    
    # Fake data
    set.seed(205)
    dat = data.frame(t=rep(1:2, each=10), 
                     pairs=rep(1:10,2), 
                     value=rnorm(20), 
                     group=rep(c("A","B"), 10))
    
    dat$value[dat$group=="A"] = dat$value[dat$group=="A"] + 6
    
    ggplot(dat %>% group_by(pairs) %>%
             mutate(slope = (value[t==2] - value[t==1])/(2-1)),
           aes(t, value, group=pairs, linetype=group, colour=slope > 0)) +
      geom_point() +
      geom_line()
    

    UPDATE: Based on your comment, it sounds like you just need to map number to an aesthetic or use faceting. Here's a facetted version using your sample data:

    df = data.frame(number, formant, time, val)
    
    # Shift val a bit
    set.seed(1095)
    df$val = df$val + rnorm(nrow(df), 0, 10)
    
    ggplot (df %>% group_by(formant, number) %>%
              mutate(slope=(val[time==99] - val[time==50])/(99-50)), 
            aes (x = time, y = val, linetype = formant, colour=slope > 0)) +
      geom_point()+
      geom_line(aes(group=interaction(formant, number))) +
      facet_grid(. ~ number)
    

    Here's another option that maps number to the size of the point markers. This doesn't look very good, but is just for illustration to show how to map variables to different "aesthetics" (colour, shape, size, etc.) in the graph.

    ggplot (df %>% group_by(formant, number) %>% 
              mutate(slope=(val[time==99] - val[time==50])/(99-50)), 
            aes (x = time, y = val, linetype = formant, colour=slope > 0)) +
      geom_point(aes(size=number))+
      geom_line(aes(group=interaction(formant, number)))
    
    0 讨论(0)
提交回复
热议问题