如何在 ggplot2 中为离散变量创建颜色渐变?

How do you create a gradient of colors for a discrete variable in ggplot2?

我有大约 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")

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

但我更喜欢从蓝色到红色的渐变。我该怎么做?

既然离散的图例无用,您可以使用连续的色标:

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

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

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

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

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