你如何在ggplot2中创建一个离散变量的颜色渐变? [英] How do you create a gradient of colors for a discrete variable in ggplot2?

查看:2392
本文介绍了你如何在ggplot2中创建一个离散变量的颜色渐变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

以下是一些示例数据和一个图。

 #示例数据:普通CDF 

库( ggplot2)

category< - 1:100
X < - seq(0,1,by = .1)
df < - data.frame(expand。网格(类别,X))
名称(df)< -c(category,X)
df< - 在(df,{
Y< - pnorm (x,mean = category / 100)
category< - factor(category)
})

#用ggplot绘制
qplot(data = df,x = X,y = Y,color = category,geom =line)

彩虹的事情(下面)

但我宁愿有一个从蓝色到红色的渐变。任何想法我可以做到这一点?

解决方案

ggplot的默认渐变函数需要一个连续的缩放比例。最简单的工作就是像@Roland建议的那样转换为连续的。您还可以使用 scale_color_manual 指定所需的任何颜色比例。您可以获得ggplot将使用的颜色列表

  cc<  -  scales :: seq_gradient_pal(blue,红色,实验室)(seq(0,1,length.out = 100))

这会将100种颜色从蓝色恢复为红色。然后,您可以在您的阴谋中使用它们

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


I have data with about 100 ordered categories. I would like to plot each category as a line separately, with the line colors ranging from a low value (say, blue) to a high value (say, red).

Here's some sample data, and a plot.

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

This produces a pretty rainbow thing (below)

but I'd rather have a gradient from blue to red. Any ideas how I can do that?

解决方案

The default gradient functions for ggplot expect a continuous scale. The easiest work around is to convert to continuous like @Roland suggested. You can also specify whatever color scale you want with scale_color_manual. You can get the list of colors ggplot would have used with

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

This returns 100 colors from blue to red. You can then use them in your plot with

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

这篇关于你如何在ggplot2中创建一个离散变量的颜色渐变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆