r - 用纯色绘制一条线,用渐变绘制第二条线

标签 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

我希望添加标签,但这可能太复杂了......

最佳答案

最简单的方法是在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

关于r - 用纯色绘制一条线,用渐变绘制第二条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53787576/

相关文章:

r - 为什么 data.table CJ 不尊重列主要顺序

html - 使 Rmarkdown 中的 htmlwidgets 移动友好

r - 如何确定 [R] 中的命名空间导入顺序

r - R中的圆形堆积条形图

r - 基于 p 值显示 LM

r - 使用 ggplot2 添加一 strip 有较少点的额外线

r - 在 R 中用返回而不是打印来抑制消息?

r - 通过 R 中的 data.table 有条件地替换组中的第一个值

r - 在 R 中使用条形图的图例格式和位置

r - 提取数据框中变量第一次出现的行