我在下面创建了一个图,其中两个图的宽度不一样,因为图例中的文本长度超过了图B中的文本长度。
我使用以下代码:
#Plot A
A<- ggplot(df_a, aes(x=Timestamp, y=Frequency, fill=Topic)) +
scale_x_date(date_breaks = '1 month', date_labels = "%b")+
geom_area(alpha=0.6 , size=1, colour="black", position = position_fill())+
ggtitle("Plot A")
# Plot B
B<- ggplot(df_b, aes(x=Timestamp, y=Frequency, fill=Topic)) +
scale_x_date(date_breaks = '1 month', date_labels = "%b")+
geom_area(alpha=0.6 , size=1, colour="black", position = position_fill())+
ggtitle("Plot B")
title=text_grob("", size = 13, face = "bold") #main title of plot
grid.arrange(grobs = list(R,Q), ncol=1, common.legend = TRUE, legend="bottom",
top = title, widths = unit(0.9, "npc"))
我甚至使用widths = unit(0.9, "npc")
作为建议的here,但它保持了两个情节的宽度,包括图例文本。因此,地块的实际宽度仍然是不相等的。
有人能指点我吗?
发布于 2022-04-11 07:31:40
您可以添加一些图A的间距图例标签,这也将保持图例键框很好地对齐,并且标签实际上是正确的。
#Plot A
A<- ggplot(df_a, aes(x=Timestamp, y=Frequency, fill=Topic)) +
scale_x_date(date_breaks = '1 month', date_labels = "%b")+
geom_area(alpha=0.6 , size=1, colour="black", position = position_fill())+
ggtitle("Plot A") +
theme(legend.spacing.x = unit(6.1, 'mm'))
# Plot B
B<- ggplot(df_b, aes(x=Timestamp, y=Frequency, fill=Topic)) +
scale_x_date(date_breaks = '1 month', date_labels = "%b")+
geom_area(alpha=0.6 , size=1, colour="black", position = position_fill())+
ggtitle("Plot B")
title=text_grob("", size = 13, face = "bold") #main title of plot
grid.arrange(grobs = list(A, B), ncol=1, common.legend = TRUE, legend="bottom",
top = title, widths = unit(0.9, "npc"))
包和使用的数据
library(gridExtra)
library(ggplot2)
library(ggpubr)
set.seed(1)
df_a <- data.frame(Timestamp = rep(seq(as.Date('2022-01-01'),
as.Date('2022-12-01'),
by = 'month'), 5),
Frequency = runif(60, 0.1, 1),
Topic = rep(LETTERS[1:5], each = 12))
df_b <- data.frame(Timestamp = rep(seq(as.Date('2022-01-01'),
as.Date('2022-12-01'),
by = 'month'), 5),
Frequency = runif(60, 0.1, 1),
Topic = rep(c('AAA', 'BBB', 'CCC', 'DDD', 'EEE'), each = 12))
https://stackoverflow.com/questions/71830287
复制