2015-07-19 61 views
5

我正嘗試在一個點上創建一個具有鮮明顏色轉換的色階。我目前在做的是:如何在ggplot2中使用銳轉換製作色階

test <- data.frame(x = c(1:20), y = seq(0.01, 0.2, by = 0.01)) 

cutoff <- 0.10 

ggplot(data = test, 
     aes(x = as.factor(x), y = y, fill = log(y), width = 1, binwidth = 0)) + 
geom_bar(stat = "identity") + 
scale_fill_gradientn(colours = c("red", "red", "yellow", "green"), 
         values = rescale(log(c(0.01, cutoff - 0.0000000000000001, cutoff, 0.2))), 
         breaks = c(log(cutoff)), label = c(cutoff)) 

它正在生產我想要的情節。但是,顏色條中斷的位置因截止點而異。有時在價值之下,有時在上面,有時在線上。這裏有一些地塊以不同的截止(0.05,0.06,0.1):

cut off at 0.05 cut off at 0.06 cut off at 0.10

我在做什麼錯?或者,有沒有更好的方法來創建這樣的色階?

回答

0

I 認爲使用scale_fill_gradientn在連續色階中獲得精確的離散截止點有點棘手。快速替代方法是使用scale_fill_gradient,將截止值設置爲limits,並使用na.value設置「超出範圍」值的顏色。

這裏有一個比你的問題稍微簡單的例子:

# some data 
df <- data.frame(x = factor(1:10), y = 1, z = 1:10) 

# a cutoff point 
lo <- 4 

ggplot(df, aes(x = x, y = y, fill = z)) + 
    geom_bar(stat = "identity") + 
    scale_fill_gradient(low = "yellow", high = "green", 
         limits = c(lo, max(df$z)), na.value = "red") 

enter image description here

正如你看到的,你的截點下面的值將不會出現在傳說中,但可以考慮包括一大塊無論如何,紅色浪費了「傳奇帶寬」。您可以在數字標題中添加紅色條的文字說明。


您也可能希望區分低於切割點和高於切割點的值。例如,將「太低」值設置爲藍色,將「太高值」設置爲紅色。這裏我使用findInterval來區分低值,中值和高值。

# some data 
set.seed(2) 
df <- data.frame(x = factor(1:10), y = 1, z = sample(1:10)) 

# lower and upper limits 
lo <- 3 
hi <- 8 

# create a grouping variable based on the the break points 
df$grp <- findInterval(df$z, c(lo, hi), rightmost.closed = TRUE) 

ggplot(df, aes(x = x, y = y, fill = z)) + 
    geom_bar(stat = "identity") + 
    scale_fill_gradient(low = "yellow", high = "green", limits = c(lo, hi), na.value = "red") + 
    geom_bar(data = df[df$grp == 0, ], fill = "blue", stat = "identity") 

enter image description here

+0

@Hengrui江難道我的回答解決問題了嗎? – Henrik

+1

感謝您的建議!對於這個問題中的例子來說,這確實是一個很好的選擇。但我在這裏看到兩個問題:1.低於截斷值的值不能被「加權」,例如,在我的小例子2中,'colors = c(「red4」,「red」,「yellow」,「green」)'''''''''''''''''''' –

相關問題