r - 如何使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
吗?
解决方案
我不知道这是否完美,但我找到了我想要的解决方案,如下所示;
首先,我准备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
推荐阅读
- python - 在文本文件中查找数字簇
- android - 无法在 AS 3.3.2 中预览状态选项卡
- python - 过滤包含冻结字符串集的 pandas 数据框列
- javascript - 在视频或 gif 中添加链接
- scala - 如何直接从 Hive 表创建 RDD?
- ruby-on-rails - 由于 LoadError: libpcap.so.0.8 导致创建数据库的 docker 问题
- python-2.7 - 如何实现下一页和上一页逻辑
- bash - 如何在 x 循环 x 秒后暂停循环
- powershell - PowerShell 脚本在粘贴到 PowerShell 窗口时运行,但在从快捷方式运行时不运行
- css - Rails 字体未在移动设备上加载但在桌面上显示