R GGPLOT2 - 线条颜色

时间:2014-09-23 14:23:24

标签: r graph colors ggplot2 line

我需要在图表中设置五种颜色,范围从黄色 - 橙色 - 红色到6行。我已经尝试了名称和十六进制数字,但它们似乎不起作用!

示例数据:

 Year EF0 EF1 EF2 EF3 EF4 EF5
 1950  13  83  71  26   7   0
 1951  25  88  82  22   5   0
 1952  24  80  72  38  20   0
 1953  66 160 143  46  22   5
 1954  91 226 193  49  11   0
 1955 169 217 167  32  12   6
 1956 125 184 149  38  21   1
 1957 218 305 238  74  25   7
 1958 145 233 154  39   4   1
 1959 143 264 157  37  11   0
 1960 128 262 175  47   6   1

当前的GGPLOT2代码

ggplot(dTorYear, aes(x=dTorYear$Year))+ 
  geom_line(aes(y = dTorYear$EF0, colour = "var5")) + 
  geom_line(aes(y = dTorYear$EF1, colour = "var4")) +
  geom_line(aes(y = dTorYear$EF2, colour = "var3")) +
  geom_line(aes(y = dTorYear$EF3, colour = "var2")) +
  geom_line(aes(y = dTorYear$EF4, colour = "var1")) +
  geom_line(aes(y = dTorYear$EF5, colour = "var0")) +
  xlab("Year") +
  ylab("Tornado Count")

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

RColorBrewer包很适合这样的事情。它将沿着定义的渐变为您生成十六进制数字。但是,代码中的主要问题是我们的颜色语句的位置,因为它是geom_line而不是aes的一部分。

将数据切换为长格式会使一切变得更加容易。

require(ggplot2)
require(reshape2)
require(RColorBrewer)

cols<-colorRampPalette(c('yellow','red'))(ncol(dTorYear)-1)

dat <- melt(dTorYear, id=c("Year"))

ggplot(dat)+
  geom_line(aes(x = Year, y = value, colour = variable)) +
  xlab("Year") +
  ylab("Tornado Count")+
  scale_colour_manual(values=c(cols))

enter image description here

答案 1 :(得分:0)

如果您融化了数据框,则可以简化ggplot调用并获取图例。

# your data
dTorYear <- read.table(text=' Year EF0 EF1 EF2 EF3 EF4 EF5
 1950  13  83  71  26   7   0
 1951  25  88  82  22   5   0
 1952  24  80  72  38  20   0
 1953  66 160 143  46  22   5
 1954  91 226 193  49  11   0
 1955 169 217 167  32  12   6
 1956 125 184 149  38  21   1
 1957 218 305 238  74  25   7
 1958 145 233 154  39   4   1
 1959 143 264 157  37  11   0
 1960 128 262 175  47   6   1', header=T)


library(reshape2)
library(ggplot2)

# color sequence, already posted by user 'charles'
cols <- colorRampPalette(colors=c('yellow', 'red'))(ncol(dTorYear)-1)

# molten data.frame
plot_df <- melt(dTorYear, id.var='Year')

# plot!
ggplot(plot_df, aes(x=Year, y=value, color=variable)) + 
  geom_line() + 
  scale_color_manual(values=cols)

enter image description here