基于因子值填充时间序列下的区域

3

我正在尝试根据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")) 

这提供了以下的图表:

plot1

我也尝试过这个:

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

结果是一团糟:

plot2

理想情况下,最终结果应该像plot1那样,其中绿色线的部分被填充。

时间序列数据可以在此处访问:

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

任何帮助将不胜感激!


2
请查看此指南中的最后一个示例,其中在geom_area()中使用ifelse()语句来实现曲线下方的填充。 - kstew
谢谢建议,我一定会尝试的。如果我成功解决了问题,我会在这里发布结果。 - Ittai Barkai
不幸的是,它似乎不起作用,或者至少我无法弄清楚如何应用它而不出错。我甚至尝试将日期转换为数字值,然后应用ifelse语句。 - Ittai Barkai
2个回答

3

好的,如果您想得到下面显示的图形,以下是我所做的。

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

# 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)

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



如需详细了解脚本,请告知。这是我完成的输出结果。 基于因子值填充时间序列下方区域

1
非常感谢!如果我有不理解的地方,我一定会问的。 - Ittai Barkai

0

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

您可以在此处查看他的教程,以更好地了解他设计的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) 

Time Series Plot


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接