首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ggplot2覆盖地块

ggplot2覆盖地块
EN

Stack Overflow用户
提问于 2014-04-26 23:12:17
回答 1查看 1.4K关注 0票数 1

如何像下面的句子所解释的那样,在ggplot2中将一个地块覆盖在另一个上面?我想用R中的ggplot2在红色的上面画灰色的时间序列(现在红色的在灰色的上面,我希望我的图是相反的)。下面是我的代码(为了向您展示我的问题,生成一些数据,真正的数据集要复杂得多):

代码语言:javascript
复制
install.packages("ggplot2")
library(ggplot2)

time <- rep(1:100,2)
timeseries <- c(rep(0.5,100),rep(c(0,1),50))
upper <- c(rep(0.7,100),rep(0,100))
lower <- c(rep(0.3,100),rep(0,100))
legend <- c(rep("red should be under",100),rep("grey should be above",100))

dataset <- data.frame(timeseries,upper,lower,time,legend)

ggplot(dataset, aes(x=time, y=timeseries)) +
  geom_line(aes(colour=legend, size=legend)) +
  geom_ribbon(aes(ymax=upper, ymin=lower, fill=legend), alpha = 0.2) +
  scale_colour_manual(limits=c("grey should be above","red should be under"),values = c("grey50","red")) +
  scale_fill_manual(values = c(NA, "red")) +
  scale_size_manual(values=c(0.5, 1.5)) +
  theme(legend.position="top", legend.direction="horizontal",legend.title = element_blank())
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-27 00:48:27

将要分组的数据转换为一个因子,并显式地设置级别的顺序。ggplot按照这个顺序绘制层。另外,将scale_manual代码分组到其应用的geom以提高可读性也是一个好主意。

代码语言:javascript
复制
legend <- factor(legend, levels = c("red should be under","grey should be above"))

c <- data.frame(timeseries,upper,lower,time,legend)

ggplot(c, aes(x=time, y=timeseries)) +
  geom_ribbon(aes(ymax=upper, ymin=lower, fill=legend), alpha = 0.2) +
  scale_fill_manual(values = c("red", NA)) +
  geom_line(aes(colour=legend, size=legend)) +
  scale_colour_manual(values = c("red","grey50")) +
  scale_size_manual(values=c(1.5,0.5)) +
  theme(legend.position="top", legend.direction="horizontal",legend.title = element_blank())

请注意,scale_manual中值的排序现在映射为“灰色”和“红色”。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23317486

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档