2

嗨,我想用红色和蓝色(代表异常)绘制两条线之间的空间,但我没有成功。仅绘制蓝色异常。
这是我的代码:

library(RCurl)
t <- getURL("https://raw.githubusercontent.com/vladamihaesei/weather_covid/master/Tab/UVanomaly.csv")## if can not download it, try manually 
t <- read.csv(text =t)
head(t)
ggplot(t, aes(x=data, y=uv1920)) + 
  geom_line(aes(y = uv1920)) + 
  geom_line(aes(y = uv01_19)) +
  geom_ribbon(data=subset(t, uv1920 <= uv01_19), 
              aes(ymin=uv1920,ymax=uv01_19), fill="blue") +
  #scale_y_continuous(expand = c(0, 0), limits=c(0,20)) +
  #scale_x_continuous(expand = c(0, 0), limits=c(0,5)) + 
  scale_x_date(date_breaks = "2 weeks", date_labels = "%d%b")+
  scale_fill_manual(values=c("red","blue"))

在此处输入图像描述

4

1 回答 1

2

填充线条之间的空间的一种方法可能看起来像这样。

基本思想是将periods中的数据拆分,可以映射到groupaes上。

不幸的是,这不是一个完美的解决方案。如您所见,我们在交叉点处有间隙。我最近做了类似的事情,用大量的手工工作来填补空白,但交叉点却少得多。也许其他人有一个更通用和可行的解决方案来解决这个问题。

t <- read.csv("https://raw.githubusercontent.com/vladamihaesei/weather_covid/master/Tab/UVanomaly.csv")

library(ggplot2)
library(dplyr)

t1 <- t %>% 
  mutate(date = as.Date(data1),
         diff = uv1920 <= uv01_19,
         period = cumsum(diff != lag(diff, default = TRUE)))
t1 %>% 
  ggplot(aes(x=date)) + 
  geom_line(aes(y = uv1920)) + 
  geom_line(aes(y = uv01_19)) +
  geom_ribbon(aes(ymin =uv1920, ymax=uv01_19, group = period, fill = diff)) +
  scale_x_date(date_breaks = "2 weeks", date_labels = "%d%b")+
  scale_fill_manual(values=c("red","blue"))

于 2020-06-29T14:20:15.517 回答