R: a simple example of a cumulative figure
This is a technical post using R.
I wrote a simple example of a cumulative and the underlying monthly data, using R.
- I called the tidyverse, ggthemes, and scales libraries.
- Then I created three column variables, Mth, Target and Actual. Mth <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), Target <- c(10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10), and Actual <- c(10, 10, 5, 2, 6, 7, 9, 10, 10, 10, 10, 10).
- Then bound the columns together into a tibble. d <- as_tibble(cbind(Mth, Target, Actual)).
- Then I calculated two cumulative variables. d <- as_tibble(d %>% mutate(cum_target = cumsum(Target), cum_actual = cumsum(Actual))).
- I then gathered the data so that the values were all in a column, and the value names in another column. dgrp <- d %>% gather("Stat", "VALUE", -Mth).
- I set the ggplot2 theme to be theme_set(theme_minimal()).
- Then I plotted the monthly actual figures: p0 <- dgrp %>% filter(Stat == "Target" | Stat == "Actual") %>% ggplot(aes(x = Mth, y= VALUE, color = Stat))+ geom_line()+ geom_point()+ theme(legend.position = "bottom", legend.text=element_text(size=10), legend.title = element_blank(), strip.text = element_text(size = 9)) + labs(x = "Month", y = "Example numbers", title = "Example Monthly", caption = paste("Source: test", sep = "")) p0.
- Then I plotted the cumulative figures. p1 <- dgrp %>% filter(Stat == "cum_target" | Stat == "cum_actual") %>% ggplot(aes(x = Mth, y= VALUE, color = Stat))+ geom_line()+ geom_point()+ theme(legend.position = "bottom", legend.text=element_text(size=10), legend.title = element_blank(), strip.text = element_text(size = 9)) + labs(x = "Month", y = "Example numbers", title = "Example Cumulative", caption = paste("Source: test", sep = "")) p1
- Then made the images: ggsave("images/p0.png", p0), and ggsave("images/p1.png", p1)
?