Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

r - Creating a vertical color gradient for a geom_bar plot

I have searched and searched, but I cant seem to find an elegant way of doing this!

I have a dataset Data consisting of Data$x (dates) and Data$y (numbers from 0 to 1)

I want to plot them in a bar-chart:

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)

The result looks like this

Click to view image

However, I wanted to give each bar a gradient in the vertical direction ranging from 0 (red) to y (greener depending on y). Is there any way of doing this smoothly?

I have tried to see if I could impose a picture on the graph as a hack, but I can't impose it on the bars only except in a super super ugly way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Doesn't exist as far as I know, but you can manipulate your data to produce it.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...