使用geom_line更改节点之间的线条颜色

时间:2017-10-24 15:06:54

标签: r ggplot2

this SO answer我构建了geom_point() geom_line()NA连接df <- data.frame( x = c(-3, -2, -1, 1, 2, 3, -3, -2, -1, 1, 2, 3), y = c(2.5, NA, 2, 3, NA, 4, 1.5, 3.5, NA, NA, 2, 1), typ = factor(c('Before x', 'Before x', 'Before x', 'After x', 'After x', 'After x', 'Before x', 'Before x', 'Before x', 'After x', 'After x', 'After x')), grp = c(rep(1, 6), rep(2, 6)) ) # df df$x2 <- with(df, ifelse(x < 0, x+.5, x-.5)) library(ggplot2) ggplot(df[!is.na(df$y),], aes(x2, y, group = grp, colour = typ)) + geom_point() + geom_line() + scale_x_continuous(breaks = c(-2.5, -1.5, -.5, 0.5, 1.5, 2.5), labels = c(-3:-1, 1:3)) + scale_fill_brewer(palette="Spectral") s。通过下面的代码和数据,我得到这样的结果:

old

然而,我希望颜色在-1和1之间的中间变化,而不是在下一个节点(可以这么说)。我想象这样的事情:

neew

我怎样才能以简单的方式做到这一点?

这是我到目前为止使用的代码。

SELECT * FROM table WHERE dateAdded > now() - interval 30 minute

1 个答案:

答案 0 :(得分:1)

正如Mako212评论的那样,你可以在两个类型之间为每组添加积分:

library(dplyr)

df2 <- df %>% 
  filter(!is.na(y)) %>% 
  select(grp, x2, y, typ)

df2 <- rbind(df2 %>% mutate(pt.alpha = 1),
             df2 %>%
               group_by(grp, typ) %>%
               arrange(x2) %>%
               mutate(isMin = x2 == min(x2),
                      isMax = x2 == max(x2)) %>%
               ungroup() %>%
               filter((typ == "Before x" & isMax) | 
                        (typ == "After x" & isMin)) %>%
               group_by(grp) %>%
               summarize(x2 = mean(x2),
                         y = mean(y)) %>%
               mutate(typ = "After x",
                      pt.alpha = 0))

> df2
   grp   x2    y      typ pt.alpha
1    1 -2.5 2.50 Before x        1
2    1 -0.5 2.00 Before x        1
3    1  0.5 3.00  After x        1
4    1  2.5 4.00  After x        1
5    2 -2.5 1.50 Before x        1
6    2 -1.5 3.50 Before x        1
7    2  1.5 2.00  After x        1
8    2  2.5 1.00  After x        1
9    1  0.0 2.50  After x        0
10   2  0.0 2.75  After x        0

绘图(线条大小增加以显示颜色变化):

ggplot(df2,
       aes(x2, y,  group = grp, colour = typ)) + 
  geom_point(aes(alpha = pt.alpha), size = 4) + 
  geom_line(size = 2) +
  scale_x_continuous(breaks = seq(-2.5, 2.5, 1), 
                     labels = c(-3:-1, 1:3)) +
  scale_alpha_identity()

plot

我没有为线条颜色指定调色板,因为它不是问题的一部分,但如果您使用的是线条颜色,则可能希望切换scale_fill_XX scale_colour_XX