R: a simple example of a cumulative figure
Source: Chris R script

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.

  1. I called the tidyverse, ggthemes, and scales libraries.
  2. 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).
  3. Then bound the columns together into a tibble. d <- as_tibble(cbind(Mth, Target, Actual)).
  4. Then I calculated two cumulative variables. d <- as_tibble(d %>% mutate(cum_target = cumsum(Target), cum_actual = cumsum(Actual))).
  5. 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).
  6. I set the ggplot2 theme to be theme_set(theme_minimal()).
  7. 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.
  8. 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
  9. Then made the images: ggsave("images/p0.png", p0), and ggsave("images/p1.png", p1)
No alt text provided for this image
No alt text provided for this image

?


要查看或添加评论,请登录

Chris Ferris的更多文章

社区洞察

其他会员也浏览了