ggplot2:根据值添加渐变彩色正方形 [英] ggplot2 : Add a gradient colored square according to values
问题描述
我有一个棘手的问题,关于我想要做什么。
我有一个两行(两个条件的平均值)的情节。我想在同一个图上添加一个反映t值的正方形(并以渐变方式根据这些值进行着色)。我怎么可以添加这个广场?
好,因为我不知道我是否清楚,这是我试图达到的数字。
感谢您的帮助!
试试这个ggplot2的方法: (-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(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 <-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 ,变量==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")
这篇关于ggplot2:根据值添加渐变彩色正方形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!