2011-04-20 119 views
3

是否可以通過審美來改變繪圖的顏色漸變?我使用類似於下面提供的代碼的代碼生成一個陰謀,並在某些情況下發現,區分各個羣體並不總是很容易。例如,在下面的圖表中,如果我可以讓A組點使用白藍色漸變,而B組點使用白紅色漸變,則更容易區分結果。改變使用ggplot2創建的散點圖上的顏色漸變

data <- data.frame(x=c(1,2,3,4,5,6,1,2,3,4,5,6), 
    y=c(1,2,3,4,5,6,1,2,3,4,5,6), grp=c(rep("A",6),rep("B",6)), 
    dt=c("2010-06-30","2010-05-31","2010-04-30", 
     "2010-03-31","2010-02-26","2010-01-29","2010-06-30", 
     "2010-05-31","2010-04-30", 
     "2010-03-31","2010-02-26","2010-01-29")) 
p <- ggplot(data, aes(x,y,color=as.integer(as.Date(data$dt)))) + 
    geom_jitter(size=4, alpha=0.75, aes(shape=grp)) + 
    scale_colour_gradient(limits=as.integer(as.Date(c("2010-01-29","2010-06-30"))), 
    low="white", high="blue") + 
    scale_shape_discrete(name="") + 
    opts(legend.position="none") 
print(p) 
+1

我不認爲你能做到這一點,至少不容易。它只是沒有映射到底層邏輯上。 – Ista 2011-04-20 22:43:02

+0

再加上一個傳說會讓人感到困惑 – hadley 2011-04-21 03:15:50

回答

6

你可以在調用ggplot2之前自己準備顏色來做到這一點。
下面是一個例子:

data$sdt <- rescale(as.numeric(as.Date(data$dt))) # data scaled [0, 1] 
cols <- c("red", "blue") # colour of gradients for each group 

# here the color for each value are calculated 
data$col <- ddply(data, .(grp), function(x) 
    data.frame(col=apply(colorRamp(c("white", cols[as.numeric(x$grp)[1]]))(x$sdt), 
     1,function(x)rgb(x[1],x[2],x[3], max=255))) 
     )$col 

p <- ggplot(data, aes(x,y, shape=grp, colour=col)) + 
    geom_jitter(size=4, alpha=0.75) + 
    scale_colour_identity() + # use identity colour scale 
    scale_shape_discrete(name="") + 
    opts(legend.position="none") 
print(p) 
+1

工作很好,謝謝。我花了一些時間才意識到grp列需要成爲一個因素,然後數據框需要按這些因素排序。 – user338714 2011-04-21 06:14:04