Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I have the following dataframe and 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 and add the 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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading