如何在ggplot2中不重叠的切片中插入文本

时间:2022-11-26 14:58:22

I am trying to create heat map in ggplot2. This is my data frame called t:

我正在尝试在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
))

When the same products belong to the same time frame, geom_text puts text on top of each other. Is there a way to do a new line character so that text are not put on top of each other in geom_text?

当相同的产品属于同一时间范围时,geom_text会将文本放在彼此的顶部。有没有办法做一个新的行字符,以便文本不在geom_text中相互叠加?

This is my ggplot2 code to create the heatmap:

这是我创建热图的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))

1 个解决方案

#1


1  

It would probably be easiest if you collapsed the data via your own transformation of the data. For example

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

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)

to get

要得到

如何在ggplot2中不重叠的切片中插入文本

#1


1  

It would probably be easiest if you collapsed the data via your own transformation of the data. For example

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

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)

to get

要得到

如何在ggplot2中不重叠的切片中插入文本