首页 > 解决方案 > 如何使geom_ribbon在ggplot2中具有渐变颜色

问题描述

我想做geom_ribbon有渐变的颜色。

例如,我有data.frame如下;

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

有了这个data.frame,我ggplot使用geom_ribbon如下

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

,这使得下面的情节;

在此处输入图像描述

在这里,我想通过 y 轴的值(即df$Depth,在这种情况下)使色带具有渐变颜色。但是,我不知道该怎么做。

我可以通过 geom_point 来做到这一点,如下所示;

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  

在此处输入图像描述

但是,我希望通过填充色带区域而不是每个点来填充色带上的颜色渐变。你有什么建议geom_ribbon吗?

标签: rdataframeggplot2

解决方案


我不知道这是否完美,但我找到了我想要的解决方案,如下所示;

首先,我准备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

其次,通过链接准备渐变背景;日志背景渐变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

三、使用绘图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

在此处输入图像描述


推荐阅读