user330860
user330860

Reputation:

ggplot2 : Add a gradient colored square according to values

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!

enter image description here

Upvotes: 10

Views: 3609

Answers (2)

Greg Snow
Greg Snow

Reputation: 49640

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

Upvotes: 0

kohske
kohske

Reputation: 66842

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

enter image description here

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

enter image description here

Upvotes: 16

Related Questions