简体   繁体   中英

Plot one line with a solid color and a second line with a gradient

I would like to plot two lines on one chart, one with a color gradient and the other a solid color. I can add individual lines and a gradient:

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

But changing the color throws an error:

> 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

I'm hoping to add labels, but that may be to complex for this...

Simplest way is to specify color for a solid line outside of 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")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM