如何在 ggplot2 中不重叠的图块中插入文本

How do you insert text in tiles that dont overlap in ggplot2

我正在尝试在 ggplot2 中创建热图。这是我的数据框 t:

structure(list(Product = structure(c(1L, 4L, 3L, 2L), .Label = c("Aplication, Database, Servers, Inf", 
"Business", "IT", "Operations"), class = "factor"), Day = structure(c(1L, 
1L, 2L, 1L), .Label = c("Tues", "Wed"), class = "factor"), Month = structure(c(1L, 
1L, 2L, 3L), .Label = c("5/1/2015", "6/1/2015", "7/1/2015"), class = "factor"), 
    Total = c(5L, 5L, 3L, 2L)), .Names = c("Product", "Day", 
"Month", "Total"), class = "data.frame", row.names = c(NA, -4L
))

当相同的产品属于同一时间范围时,geom_text 会将文本放在彼此的顶部。有没有办法做一个换行符,这样文本就不会在 geom_text 中彼此重叠?

这是我创建热图的 ggplot2 代码:

ggplot(t, aes(x=Month, y=Day)) + geom_tile(aes(order=Day, fill=Total), limits=c("Mon","Fri"),size=1)+
  theme(legend.position=c("none"))+
  geom_text(size=2.5,aes(label=Product))

如果您通过自己的数据转换来折叠数据,这可能是最简单的。例如

ggplot(t, aes(x=Month, y=Day)) + 
  geom_tile(aes(order=Day, fill=Total), limits=c("Mon","Fri"),size=1)+
  theme(legend.position=c("none"))+
  geom_text(data=aggregate(Product~Month+Day, t, paste, collapse="\n"), 
    aes(label=Product), size=2.5)

得到