且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ggplot2:根据值添加渐变彩色正方形

更新时间:2022-10-19 13:30:30

试试这个ggplot2的方法: (-10,10,0.1)
df df $ t dfm
ggplot(NULL,aes(x,value))+
geom_line(aes(color = variable),
小滴(子集(dfm,变量%in%c(y1,y2 )))+
geom_rect(aes(xmin = x - 0.05,xmax = x + 0.05,ymin = -0.5,ymax = -0.4,fill = value),
子集(dfm,variable ==t))


更新



您可以使用 scale_fill_XXX 。这里是一个喷墨颜色版本:

  jet.colors<  -  colorRampPalette(c(#00007F,blue ,#007FFF,青色,#7FFF7F,黄色,#FF7F00,红色,#7F0000))

# $ bp geom_line(aes(color = variable),
小滴(子集(dfm,变量%in%c(y1, y2)))+
geom_rect(aes(xmin = x-0.05,xmax = x + 0.05,ymin = -0.5,ymax = -0.4,fill = value),
子集(dfm ,变量==t))+
scale_fill_gradientn(colors = jet.colors(7))
p

,而在ggplot2的下一个版本中,您可以使用colorbar作为图例。

 #面板在右侧
p + guides(fill =colourbar)


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!

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