【问题标题】:How do you create a gradient of colors for a discrete variable in ggplot2?如何为 ggplot2 中的离散变量创建颜色渐变?
【发布时间】:2023-03-21 13:57:01
【问题描述】:

我有大约 100 个有序类别的数据。我想将每个类别分别绘制为一条线,线的颜色范围从低值(比如蓝色)到高值(比如红色)。

这是一些示例数据和图表。

# Example data: normal CDFs

library(ggplot2)

category <- 1:100
X <- seq(0, 1, by = .1)
df <- data.frame(expand.grid(category, X))
names(df) <- c("category", "X")
df <- within(df, {
  Y <- pnorm(X, mean = category / 100)
  category <- factor(category)
  })

# Plot with ggplot
qplot(data = df, x = X, y = Y, color = category, geom = "line")

这会产生一个漂亮的彩虹(下)

但我更喜欢从蓝色到红色的渐变。有什么想法可以做到吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    ggplot 的默认梯度函数需要一个连续的尺度。最简单的解决方法是像@Roland 建议的那样转换为连续的。您还可以使用scale_color_manual 指定您想要的任何颜色比例。您可以获得 ggplot 将使用的颜色列表

    cc <- scales::seq_gradient_pal("blue", "red", "Lab")(seq(0,1,length.out=100))
    

    这会返回从蓝色到红色的 100 种颜色。然后你可以在你的情节中使用它们

    qplot(data = df, x = X, y = Y, color = category, geom = "line") +     
        scale_colour_manual(values=cc)
    

    【讨论】:

    • 我的 gggplot 告诉我 Non Lab interpolation is deprecated,显然这现在只适用于双色渐变。
    【解决方案2】:

    由于离散图例无论如何都没用,您可以使用连续色标:

    ggplot(data = df, aes(x = X, y = Y, color = as.integer(category), group = category)) +
      geom_line() +
      scale_colour_gradient(name = "category", 
                            low = "blue", high = "red")
    

    【讨论】:

    • 谢谢,但在实际数据中,我正在处理日期。我会看看我是否可以使连续图例与日期值看起来合情合理。
    • 日期是连续数据。
    猜你喜欢
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2019-05-14
    相关资源
    最近更新 更多