ggplot2:根据值添加渐变色方块

时间:2012-01-05 12:53:58

标签: r ggplot2 gradient

关于我正在尝试做什么,我有一个棘手的问题。 我有一个带有两条线(两个条件的平均值)的图。我想在同一个图上添加一个反映t值的正方形(并以渐变方式根据这些值着色)。我怎么能添加这个方块?

好吧,因为我不知道我是否清楚,这是我试图实现的数字。

感谢您的帮助!

enter image description here

2 个答案:

答案 0 :(得分:17)

尝试使用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的下一个版本中,您可以使用colorbar作为图例。

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

enter image description here

答案 1 :(得分:0)

对于基本图形,您可以使用rasterImage功能将带有渐变的矩形添加到图形中。