为geom_bar绘图创建垂直颜色渐变

时间:2018-01-11 15:11:34

标签: r plot ggplot2 geom-bar

我已经搜索过,但我似乎无法找到一种优雅的方式来做到这一点!

我有一个由Data(日期)和Data$x组成的数据集Data$y(0到1之间的数字)

我想在条形图中绘制它们:

ggplot(Data) + geom_bar(aes(x = x, y = y, fill = y, stat = "identity")) +
   scale_fill_gradient2(low = "red", high = "green", mid = "yellow", midpoint = 0.90)

结果如下所示

Click to view image

但是,我想给每个条形在垂直方向上的渐变范围从0(红色)到y(绿色取决于y)。有没有办法顺利地做到这一点?

我试图看看我是否可以将图片强加到图表上作为黑客攻击,但除​​了以超级丑陋的方式外,我不能将它强加在条形图上。

2 个答案:

答案 0 :(得分:1)

据我所知不存在,但您可以操纵数据来生成它。

library(ggplot2)

df = data.frame(x=c(1:10),y=runif(10))

prepGradient <- function(x,y,spacing=max(y)/100){
  stopifnot(length(x)==length(y))
  df <- data.frame(x=x,y=y)
  newDf = data.frame(x=NULL,y=NULL,z=NULL)
  for (r in 1:nrow(df)){
    n <- floor(df[r,"y"]/spacing)
    for (s in c(1:n)){
      tmp <- data.frame(x=df[r,"x"],y=spacing,z=s*spacing)
      newDf <- rbind(newDf,tmp)
    }
    tmp <- data.frame(x=df[r,"x"],y=df[r,"y"]%%spacing,z=df[r,"y"])
    newDf <- rbind(newDf,tmp)
  }
  return(newDf)
}

df2 <- prepGradient(df$x,df$y)

ggplot(df2,aes(x=x,y=y,fill=z)) + 
  geom_bar(stat="identity") + 
  scale_fill_gradient2(low="red", high="green", mid="yellow",midpoint=median(df$y))+
  ggtitle('Vertical Gradient Example') +
  theme_minimal()

enter image description here

答案 1 :(得分:1)

另一个,不是很漂亮,黑客使用geom_segment。 x开始和结束位置(xxend)是硬编码的(- 0.4; + 0.4),size也是如此。需要根据x值的数量和y的范围来调整这些数字。

# some toy data
d <- data.frame(x = 1:3, y = 1:3)

# interpolate values from zero to y and create corresponding number of x values
vals <- lapply(d$y, function(y) seq(0, y, by = 0.01))
y <- unlist(vals)
mid <- rep(d$x, lengths(vals))
d2 <- data.frame(x = mid - 0.4,
                 xend = mid + 0.4,
                 y = y,
                 yend = y)

ggplot(data = d2, aes(x = x, xend = xend, y = y, yend = yend, color = y)) +
  geom_segment(size = 2) +
  scale_color_gradient2(low = "red", mid = "yellow", high = "green", 
                        midpoint = max(d2$y)/2) 

enter image description here

一个有点相关的问题可能会给你一些其他想法:How to make gradient color filled timeseries plot in R