2012-01-05 63 views
10

我有一個棘手的問題,關於我想要做什麼。 我有兩條線(兩個條件的意思)在它上面的情節。我想在同一個圖上添加一個反映t值的正方形(並以漸變方式根據這些值進行着色)。我怎麼能添加這個廣場?ggplot2:根據值添加漸變彩色正方形

那麼,因爲我不知道我是否清楚,這裏是我試圖實現的一個數字。

謝謝你的幫助!

enter image description here

+1

請問您可以發佈一些可重複的例子嗎? – 2012-01-05 13:00:18

回答

16

嘗試此GGPLOT2方式:

x <- seq(-10, 10, 0.1) 
df <- data.frame(x, y1 = pnorm(x), y2 = pnorm(x) * 2) 
df$t <- df$y2 - df$y1 
dfm <- melt(df, id = "x") 

ggplot(NULL, aes(x, value)) + 
    geom_line(aes(colour = variable), 
      droplevels(subset(dfm, variable %in% c("y1", "y2")))) + 
    geom_rect(aes(xmin = x - 0.05, xmax = x + 0.05, ymin = -0.5, ymax = -0.4, fill = value), 
      subset(dfm, variable == "t")) 

enter image description here

修訂

您可以使用scale_fill_XXX。這裏是一個噴色版:

jet.colors <- colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan","#7FFF7F", "yellow", "#FF7F00", "red", "#7F0000")) 

# panel on the left side 
p <- ggplot(NULL, aes(x, value)) + 
    geom_line(aes(colour = variable), 
      droplevels(subset(dfm, variable %in% c("y1", "y2")))) + 
    geom_rect(aes(xmin = x - 0.05, xmax = x + 0.05, ymin = -0.5, ymax = -0.4, fill = value), 
      subset(dfm, variable == "t")) + 
    scale_fill_gradientn(colours = jet.colors(7)) 
p 

和GGPLOT2的下一個版本,你可以使用彩條的傳奇。

# panel on the right side 
    p + guides(fill = "colourbar") 

enter image description here

+0

非常感謝你真的很好!反問題:你會知道我可以怎樣操縱漸變的顏色嗎?非常感謝! – clowny 2012-01-05 14:00:27

+1

@clowny更新。 – kohske 2012-01-05 14:13:40

+1

我會建議'geom_raster'而不是'geom_rect' – baptiste 2012-01-05 20:06:01

0

對於鹼的圖形就可以使用rasterImage函數來添加一個矩形與它的梯度的曲線圖。