Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill area under time series based on factor value

I am trying to fill the area under a time series line based on a factor value of 0 and 1. The area should only be filled if the value is equal to 1.

I have managed to colour code the time series line based on the factor value with the following code:

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

This provides the following graph:

plot1

I have also tried this:

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

which comes out as a complete mess:

plot2

Ideally the final result should look like plot1 where the parts of the line in green are filled.

The time series data can be accessed here:

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

Any help would be greatly appreciated!

like image 711
Ittai Barkai Avatar asked Jan 19 '26 18:01

Ittai Barkai


1 Answers

Okay, here is what I did to get the graph shown below if that is what you want.

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

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

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


Let me know if you need elaboration to understand the script. Attached is the output in my end. Fill area under time series based on factor value

like image 176
deepseefan Avatar answered Jan 22 '26 06:01

deepseefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!