如何在 R 中按条件将标题添加到 ggplot 图?

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

我有以下数据框和基于它的堆积面积图:

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)

现在我想根据数据框中的最早年份自动执行向图表添加标题的过程,所以我想以某种方式编写代码: “自 min(df$Year) 以来的销售额(按类别)”。

您可以在 ggtitle()labs(title = ) 函数中使用 paste

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

数据

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