ggplot2 : Add a gradient colored square according to values

六眼飞鱼酱① 提交于 2019-12-03 07:34:52

问题


I have a tricky question regarding to what i'm trying to do. I have a plot with two lines (the mean of two conditions) on it. I want to add on the same plot a square reflecting the t-values (and colored according to these values in a gradient way). How could i add this square?

Well since i don't know if i'm clear, here is a figure of what i try to achieve.

Thank you for any help!


回答1:


Try this for ggplot2 way:

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"))

UPDATED

You can use scale_fill_XXX. Here is a jet-color version:

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

and in the next version of ggplot2, you can use colorbar as the legend.

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




回答2:


For base graphics you can use the rasterImage function to add a rectangle with the gradient in it to a graph.



来源:https://stackoverflow.com/questions/8742804/ggplot2-add-a-gradient-colored-square-according-to-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!