根据因子值填充时间序列下的区域

Fill area under time series based on factor value

我正在尝试根据系数值 0 和 1 填充时间序列线下的区域。只有当值等于 1 时才应填充该区域。

我已经设法使用以下代码根据因子值对时间序列线进行颜色编码:

install.packages("scales")
library("scales")
library("ggplot2")
ggplot(plot.timeseries) +
  geom_line(aes(x = Date, y = Price, color = Index, group = 1)) +
  scale_x_date(labels = date_format("%Y"), breaks = date_breaks("years")) + 
  scale_colour_manual(values = c("red3", "green3")) 

这提供了下图:

我也试过这个:

ggplot(plot.timeseries, aes(x=Date, y = Price, fill=Index)) +
  geom_area(alpha=0.6) +
  theme_classic() +
  scale_fill_manual(values=c("#999999", "#32CD32"))

结果一团糟:

理想情况下,最终结果应类似于 plot1,其中填充了绿色线条的部分。

时间序列数据可以在这里访问:

https://drive.google.com/file/d/1qWsuJk41_fJZktLCAZSgfGvoDLqTt-jk/view?usp=sharing

如有任何帮助,我们将不胜感激!

好的,如果这是您想要的,这就是我为得到下图所做的工作。

# -------------------------------------------------------------------------

# load required packages # 

library(scales)
library("ggplot2")
library(dplyr)

# -------------------------------------------------------------------------
# load the data to a df #
plot.timeseries <- get(load("TimeSeries_Data.RData"))

# -------------------------------------------------------------------------

# transform the data (my_fill_color will have green and NA values)
my_object <- plot.timeseries %>%
  select(Price, Index, Date) %>%
  mutate(Index_ord_factor = factor(Index, levels = unique(Index), ordered=TRUE),
         my_fill_color = case_when(
           Index_ord_factor > 0   ~ "green" # ordered factor enables the '>' operation
         ))

# -------------------------------------------------------------------------

# Plot your graph using the transformed data

ggplot(my_object, mapping = aes(x=Date, y=Price)) +
  geom_line(aes(color = Index, group = 1))+
  geom_col(fill =my_object$my_fill_color, width = 1)

# -------------------------------------------------------------------------


如果您需要详细说明以理解脚本,请告诉我。附件是我最后的输出。

对于那些感兴趣的人,我还从 Erik Chacon 那里收到了这个替代解决方案。

您可以查看他的教程 here 以更好地了解他设计的 ggplot2 扩展,此解决方案中使用了该扩展。

    # Installing and loading necessary packages
    install.packages("remotes")
    remotes::install_github("ErickChacon/mbsi")
    library(mbsi)
    library(ggplot2)

    load("timeseries.RData")

    #converting factor to numeric
    plot.timeseries$Index <- as.numeric(levels(plot.timeseries$Index))[plot.timeseries$Index] 

     ggplot(plot.timeseries, aes(Date, Price)) +
        geom_line() +
        stat_events(aes(event = I(1 * (Index > 0)), fill = "Index"),
              threshold = min(plot.timeseries$Price),
              fill = "green", alpha = 0.3)