imtaiky
imtaiky

Reputation: 323

How to make geom_ribbon have gradation color in ggplot2

I would like to make geom_ribbon have gradation color.

For example, I have data.frame as below;

df <-data.frame(Day = c(rnorm(300, 3, 2.5), rnorm(150, 7, 2)), # create random data
                Depth = c(rnorm(300, 6, 2.5), rnorm(150, 2, 2)),
                group = c(rep('A', 300), rep('B', 150))) # add two groups

With this data.frame, I make ggplot using geom_ribbon as below

gg <-
  ggplot(data=df,aes(x=Day))+  
  geom_ribbon(aes(ymin=Depth,ymax=max(Depth)),alpha = 0.25)+
  ylim(max(df$Depth),0)+
  facet_wrap(~group,scales = "free_x",ncol=2)+
  labs(x="Days(d)",y="Depth (m)")
gg

, which makes a following plot;

enter image description here

Here, I would like to make the ribbon have gradation color by the value of y-axis (i.e. df$Depth, in this case). However, I do not how to do it.

I can do it by geom_point as below;

gg <- gg + 
  geom_point(aes(y=Depth,color=Depth),alpha = 1, shape = 20, size=5)+
  scale_color_gradient2(midpoint = 5, 
                        low = "red", mid="gray37", high = "black",
                        space ="Lab")
gg  

enter image description here

But, I want the color gradation on ribbon by filling the ribbon area, not on each point. Do you have any suggestion to do it with geom_ribbon?

Upvotes: 0

Views: 1268

Answers (1)

imtaiky
imtaiky

Reputation: 323

I do not know this is perfect, but I found a solution for what I want as follows;

First, I prepare data.frame;

df <-data.frame(Day = c(rnorm(300, 7, 2), rnorm(150, 5, 1)), # create random data
                Depth = c(rnorm(300, 10, 2.5), rnorm(150, 7, 2)),
                group = c(rep('A', 300), rep('B', 150))) # add two groups

Second, prepare the gradation background by following the link; log background gradient ggplot

xlength <- ceiling(max(df$Day))
yseq <- seq(0,max(df$Depth), length=100)
bg <- expand.grid(x=0:xlength, y=yseq) # dataframe for all combinations

Third, plot by using ggplot2;

gg <- ggplot() +  
  geom_tile(data=bg, 
            aes(x=x, y=y, fill=y),
            alpha = 0.75)+ # plot the gradation
  scale_fill_gradient2(low='red', mid="gray37", high = "black", 
                        space ="Lab",midpoint = mean(df$Depth)/2)+ #set the color
  geom_ribbon(data=df,
              aes(x=Day,ymin=0,ymax=Depth),
              fill = "gray92")+ #default ggplot2 background color
  ylim(max(df$Depth),0)+
  scale_x_continuous()+
  facet_wrap(~group,scales = "free_x",ncol=2)+
  labs(x="Days(d)",y="Depth (m)")+
  theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank())  

 gg

enter image description here

Upvotes: 1

Related Questions