用纯色绘制一条线,用渐变绘制另一条线

时间:2018-12-14 22:15:16

标签: r ggplot2

我想在一张图表上绘制两条线,一条带有颜色渐变,另一条带有纯色。我可以添加单独的线条和渐变:

x <- seq(1, 100, 1)
y <- rnorm(100, 50, 15)
z <- rnorm(100, 30, 5)
df <- data.frame(x,y,z)

library(ggplot2)   
ggplot(df, aes(x = x, y = y, color = x)) + geom_line() +
  scale_color_gradient(low = "blue", high = "red") +
  geom_line(data = df, aes(x = x, y = z, color = x))

但是更改颜色会引发错误:

> ggplot(df, aes(x = x, y = y, color = ..y..)) + geom_line() +
+   scale_color_gradient(low = "blue", high = "red") +
+   geom_line(aes(x = x, y = z, color = "yellow"))
Error: Discrete value supplied to continuous scale

我希望添加标签,但这可能会很复杂...

1 个答案:

答案 0 :(得分:6)

最简单的方法是为aes之外的实线指定颜色:

library(ggplot2)
ggplot(df, aes(x, y, color = x)) + 
    geom_line() +
    # No need to respecify data or x at it's defined in main ggplot call
    geom_line(aes(y = z), color = "yellow") +
    scale_color_gradient(low = "blue", high = "red")

enter image description here