绘制具有多个彩色部分的不同彩色线条

时间:2018-03-08 17:51:36

标签: r ggplot2

我想要一个线条图,其中我有2条线,有2种不同的颜色,每条线的部分颜色都是不同颜色的颜色。像每条线的渐变色调。例如沿x轴的不同区域的蓝色阴影线

library(ggplot2)
df <- data.frame(a = c(rep(0,10), rep(1,10)),
                 b = c(rep(c(rep(0,3),rep(1,4),rep(2,3)), 2)),
                 c = sample(1:20),
                 d = c(1:20))
df

ggplot(data = df) + geom_line(aes(x = d, y = c, color = factor(a),
linetype = factor(b)))

enter image description here 在这里,我得到不同颜色的每一行。尝试为每个部分添加不同的线型,但这不起作用。每行应根据列b

具有不同的阴影

2 个答案:

答案 0 :(得分:1)

您可以尝试使用alpha和line size而不是linetype。

代码:

library(ggplot2)
ggplot(df) + 
    geom_line(aes(d, c, 
                  color = factor(a), group = a,
                  size = factor(b), alpha = factor(b))) +
    scale_alpha_manual(values = c(1, 0.6, 0.2)) +
    scale_size_manual(values = c(2, 1, 0.5))

结果:

enter image description here

数据(df):

structure(list(a = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1), b = c(0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 0, 0, 
0, 1, 1, 1, 1, 2, 2, 2), c = c(6L, 13L, 10L, 20L, 2L, 11L, 15L, 
5L, 3L, 7L, 17L, 4L, 12L, 14L, 1L, 19L, 9L, 8L, 18L, 16L), d = 1:20), .Names = c("a", 
"b", "c", "d"), row.names = c(NA, -20L), class = "data.frame")

答案 1 :(得分:0)

这种方法怎么样:

创建一个从蓝色到红色的8种颜色的斜坡,使用前3种颜色来映射蓝色,最后3种颜色来映射红色。基于a和b的相互作用的颜色:

colfunc <- colorRampPalette(c("blue", "red"))

ggplot(data = df)+
  geom_line(aes(x = d, y = c, color = interaction(b, a), group = a)) +
  scale_color_manual(values = colfunc(8)[c(1:3,6:8)])

enter image description here

或类似的东西:

bfunc <- colorRampPalette(c("blue3", "dodgerblue", "firebrick1", "darkred"))

ggplot(data = df)+
  geom_line(aes(x = d, y = c, color = interaction(b, a), group = a)) +
  scale_color_manual(values = bfunc(6))

enter image description here