2012-01-05 119 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函数来添加一个矩形与它的梯度的曲线图。