如何更改ggplot中表示变量范围的线条的颜色?

时间:2016-06-24 02:17:15

标签: r ggplot2

我有一个名为cpp的数据框(在下面的链接中提供的Rdata文件中)。我想在我的绘图中为下面列出的值范围设置颜色。我尝试使用下面的代码,但由于某种原因,它没有按预期分离线条颜色。如果你看一下p2图,颜色图例与线条的颜色和{{不一致。 1}}列。有人可以帮助我。

Rdata文件: https://dl.dropboxusercontent.com/u/43417085/mydata.RData

cutoff

1 个答案:

答案 0 :(得分:1)

您无法直接在aestetics aes()中传递颜色名称。 相反,将字符向量(例如color)传递给scale_color_manual()(请参阅文档here)。

我已将cutoff列中的颜色名称替换为字母,但如果您相应地命名color字符向量,也可以保留颜色名称。

这应该提供所需的result

library(data.table)
library(ggplot2)
library(dplyr)
#setting colour for the range of values
cpp$cutoff <- NA
cpp$cutoff["A" <- cpp$mybs <= -0.1] <- "A" 
cpp$cutoff["B" <- cpp$mybs > -0.1 &  cpp$mybs<= 0.1] <- "B" 
cpp$cutoff["C" <- cpp$mybs > 0.1 &  cpp$mybs<= 0.22] <- "C" 
cpp$cutoff["D" <- cpp$mybs > 0.22 &  cpp$mybs<= 0.27] <- "D" 
cpp$cutoff["E" <- cpp$mybs > 0.27 &  cpp$mybs<= 0.46] <- "E" 
cpp$cutoff["F" <- cpp$mybs > 0.46 &  cpp$mybs<= 0.56] <- "F" 
cpp$cutoff["G" <- cpp$mybs > 0.56 &  cpp$mybs<= 0.9] <- "G" 
cpp$cutoff["H" <- cpp$mybs > 0.9 &  cpp$mybs<= 1.25] <- "H" 
cpp$cutoff["I" <- cpp$mybs > 1.25] <- "I" 

##plotting here
p<- ggplot(cpp, aes(x = my_good, y = mybs, group = key, color = cutoff)) +
  geom_line() + geom_point()  #to show the dots


p1 <- p+labs(title="Threshold", x="Number wanted", y="mybs") +

  theme_bw() +
  theme(axis.text.x=element_text(size=14), axis.title.x=element_text(size=16),
        axis.text.y=element_text(size=14), axis.title.x=element_text(size=16),
        plot.title=element_text(size=20, face="bold", color="darkgreen"))

p2 <-p1+ scale_x_continuous(expand = c(0, 0), breaks = c(0, 1500, seq(5000, max(as.data.frame(cpp[,"my_good"])), 10000)),
                            labels = c(0, 1500, seq(5000, max(as.data.frame(cpp[,"my_good"])),10000)))  #expand forces the origin to start at zero

# construct the named character vector to pass to scale_color_manual
color <- c("A" = "forestgreen", 
           "B" = "yellow1", "C" = "slateblue2", 
           "D" = "navy", "E" = "black", 
           "F" = "navy" , "G" = "red2", 
           "H" = "navy" , "I" = "red2")

# plot p1 with the colors defined
p1 + scale_color_manual(values = color)