基于“多个因素”改变ggplot中的线条颜色坡 [英] Changing line color in ggplot based on "several factors" slope

查看:143
本文介绍了基于“多个因素”改变ggplot中的线条颜色坡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:
我有以下数据,我想根据3个因子的斜率(I,II,III)在组之间画一条线。 p>

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

我尝试了以下方法,但无法设置连接改变连接I - III和II - III的线的颜色:

  ggplot( (value)[t ==I]  -  value [t ==I])/(value [t == ()) -  value [t ==I]),
aes(t,value,group = pairs,linetype = group,color = slope> 0))+
geom_point() +
geom_line()

这与



由于 dat 中的数据按 t 排序,因此我使用 diff 来计算斜率。

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.

解决方案

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()

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

这篇关于基于“多个因素”改变ggplot中的线条颜色坡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆