Search code examples
rggplot2plottidyversedata-visualization

How to add Title to ggplot graph by condition in R?


I have the following dataframe and a stacked area chart based on it:

df <- data.frame (Year  = c("2010", "2010",  "2010", "2010", "2011","2011","2011","2011","2012","2012","2012","2012","2013","2013","2013","2013"),
                  Sales = c(100000000,200000000,50000000,500000000,400000000,200000000,400000000,145000000,100000000,456000000,345000000,321000000,100000000,200000000,250000000,400000000),
                 Category = c("A", "B",  "C", "D","A", "B",  "C", "D","A", "B",  "C", "D","A", "B",  "C", "D"))

df$Year <- as.integer(df$Year)

df %>% 
  ggplot(aes(x = Year, y = Sales, fill = Category)) +
  geom_area() + scale_x_continuous(breaks=2010:2013)

Now I want to automate the process to add a title to the chart based on the earliest year in the dataframe, so somehow I want to code this: "Sale since min(df$Year) by categories".


Solution

  • You can use a paste in ggtitle() or labs(title = ) function.

    library(dplyr)
    library(ggplot2)
    
    df %>% 
      ggplot(aes(x = Year, y = Sales, fill = Category)) +
      geom_area() + 
      scale_x_continuous(breaks=2010:2013) +
      ggtitle(paste("Sale since", min(df$Year), "by categories"))
    

    Data

    df <- structure(list(Year = c(2010L, 2010L, 2010L, 2010L, 2011L, 2011L, 
    2011L, 2011L, 2012L, 2012L, 2012L, 2012L, 2013L, 2013L, 2013L, 
    2013L), Sales = c(1e+08, 2e+08, 5e+07, 5e+08, 4e+08, 2e+08, 4e+08, 
    1.45e+08, 1e+08, 4.56e+08, 3.45e+08, 3.21e+08, 1e+08, 2e+08, 
    2.5e+08, 4e+08), Category = c("A", "B", "C", "D", "A", "B", "C", 
    "D", "A", "B", "C", "D", "A", "B", "C", "D")), row.names = c(NA, 
    -16L), class = "data.frame")