gpt4 book ai didi

r - 当一些图有图例而其他图没有时,在 ggplot2 中对齐多个图

转载 作者:行者123 更新时间:2023-12-03 10:53:58 25 4
gpt4 key购买 nike

我已经使用了here所示的方法对齐共享相同横坐标的图形。

但是当我的一些图表有图例而其他图表没有时,我无法让它工作。

下面是一个例子:

library(ggplot2)
library(reshape2)
library(gridExtra)

x = seq(0, 10, length.out = 200)
y1 = sin(x)
y2 = cos(x)
y3 = sin(x) * cos(x)

df1 <- data.frame(x, y1, y2)
df1 <- melt(df1, id.vars = "x")

g1 <- ggplot(df1, aes(x, value, color = variable)) + geom_line()
print(g1)

df2 <- data.frame(x, y3)
g2 <- ggplot(df2, aes(x, y3)) + geom_line()
print(g2)

gA <- ggplotGrob(g1)
gB <- ggplotGrob(g2)
maxWidth <- grid::unit.pmax(gA$widths[2:3], gB$widths[2:3])
gA$widths[2:3] <- maxWidth
gB$widths[2:3] <- maxWidth
g <- arrangeGrob(gA, gB, ncol = 1)
grid::grid.newpage()
grid::grid.draw(g)

使用此代码,我得到以下结果:

enter image description here

我想要的是对齐 x 轴,并用空白填充缺失的图例。这可能吗?

编辑:

提出的最优雅的解决方案是下面 Sandy Muspratt 提出的解决方案。

我实现了它,它在两个图形上运行得很好。

然后我尝试了三个,具有不同的图例大小,但它不再起作用:
library(ggplot2)
library(reshape2)
library(gridExtra)

x = seq(0, 10, length.out = 200)
y1 = sin(x)
y2 = cos(x)
y3 = sin(x) * cos(x)
y4 = sin(2*x) * cos(2*x)

df1 <- data.frame(x, y1, y2)
df1 <- melt(df1, id.vars = "x")

g1 <- ggplot(df1, aes(x, value, color = variable)) + geom_line()
g1 <- g1 + theme_bw()
g1 <- g1 + theme(legend.key = element_blank())
g1 <- g1 + ggtitle("Graph 1", subtitle = "With legend")

df2 <- data.frame(x, y3)
g2 <- ggplot(df2, aes(x, y3)) + geom_line()
g2 <- g2 + theme_bw()
g2 <- g2 + theme(legend.key = element_blank())
g2 <- g2 + ggtitle("Graph 2", subtitle = "Without legend")

df3 <- data.frame(x, y3, y4)
df3 <- melt(df3, id.vars = "x")

g3 <- ggplot(df3, aes(x, value, color = variable)) + geom_line()
g3 <- g3 + theme_bw()
g3 <- g3 + theme(legend.key = element_blank())
g3 <- g3 + scale_color_discrete("This is indeed a very long title")
g3 <- g3 + ggtitle("Graph 3", subtitle = "With legend")

gA <- ggplotGrob(g1)
gB <- ggplotGrob(g2)
gC <- ggplotGrob(g3)

gB = gtable::gtable_add_cols(gB, sum(gC$widths[7:8]), 6)

maxWidth <- grid::unit.pmax(gA$widths[2:5], gB$widths[2:5], gC$widths[2:5])
gA$widths[2:5] <- maxWidth
gB$widths[2:5] <- maxWidth
gC$widths[2:5] <- maxWidth

g <- arrangeGrob(gA, gB, gC, ncol = 1)
grid::grid.newpage()
grid::grid.draw(g)

这导致下图:
enter image description here

我在这里找到的答案以及有关该主题的其他问题的主要问题是人们“玩”了很多向量 myGrob$widths没有真正解释他们为什么这样做。我见过有人修改 myGrob$widths[2:5]其他 myGrob$widths[2:3]我只是找不到任何解释这些列是什么的文档。

我的目标是创建一个通用函数,例如:
AlignPlots <- function(...) {
# Retrieve the list of plots to align
plots.list <- list(...)

# Initialize the lists
grobs.list <- list()
widths.list <- list()

# Collect the widths for each grob of each plot
max.nb.grobs <- 0
longest.grob <- NULL
for (i in 1:length(plots.list)){
if (i != length(plots.list)) {
plots.list[[i]] <- plots.list[[i]] + theme(axis.title.x = element_blank())
}

grobs.list[[i]] <- ggplotGrob(plots.list[[i]])
current.grob.length <- length(grobs.list[[i]])
if (current.grob.length > max.nb.grobs) {
max.nb.grobs <- current.grob.length
longest.grob <- grobs.list[[i]]
}

widths.list[[i]] <- grobs.list[[i]]$widths[2:5]
}

# Get the max width
maxWidth <- do.call(grid::unit.pmax, widths.list)

# Assign the max width to each grob
for (i in 1:length(grobs.list)){
if(length(grobs.list[[i]]) < max.nb.grobs) {
grobs.list[[i]] <- gtable::gtable_add_cols(grobs.list[[i]],
sum(longest.grob$widths[7:8]),
6)
}
grobs.list[[i]]$widths[2:5] <- as.list(maxWidth)
}

# Generate the plot
g <- do.call(arrangeGrob, c(grobs.list, ncol = 1))

return(g)
}

最佳答案

扩展@Axeman 的答案,您可以使用 cowplot 完成所有这些操作无需使用 draw_plot直接地。本质上,您只需将图分成两列——一列用于绘图本身,另一列用于图例——然后将它们并排放置。请注意,因为 g2没有传说,我用的是空的 ggplot对象以在图例列中保留该图例的位置。

library(cowplot)

theme_set(theme_minimal())

plot_grid(
plot_grid(
g1 + theme(legend.position = "none")
, g2
, g3 + theme(legend.position = "none")
, ncol = 1
, align = "hv")
, plot_grid(
get_legend(g1)
, ggplot()
, get_legend(g3)
, ncol =1)
, rel_widths = c(7,3)
)



enter image description here

在我看来,这里的主要优势是能够根据需要为每个子图设置和跳过图例。

值得注意的是,如果所有的情节都有一个图例, plot_grid为您处理对齐:
plot_grid(
g1
, g3
, align = "hv"
, ncol = 1
)



enter image description here

只是 g2中缺失的图例这会导致问题。

因此,如果您将虚拟图例添加到 g2并隐藏它的元素,你可以得到 plot_grid为你做所有的对齐,而不用担心手动调整 rel_widths如果你改变输出的大小
plot_grid(
g1
, g2 +
geom_line(aes(color = "Test")) +
scale_color_manual(values = NA) +
theme(legend.text = element_blank()
, legend.title = element_blank())
, g3
, align = "hv"
, ncol = 1
)



enter image description here

这也意味着您可以轻松拥有多个列,但仍保持绘图区域相同。只需删除 , ncol = 1从上面生成一个包含 2 列的图,但仍然正确间隔(尽管您需要调整纵横比以使其可用):

enter image description here

正如@baptiste 所建议的那样,您还可以通过添加 theme(legend.justification = "left") 来移动图例,使它们都与图的“图例”部分的左侧对齐。到带有图例的图(或在 theme_set 中全局设置),如下所示:
plot_grid(
g1 +
theme(legend.justification = "left")
,
g2 +
geom_line(aes(color = "Test")) +
scale_color_manual(values = NA) +
theme(legend.text = element_blank()
, legend.title = element_blank())
, g3 +
theme(legend.justification = "left")
, align = "hv"
, ncol = 1
)



enter image description here

关于r - 当一些图有图例而其他图没有时,在 ggplot2 中对齐多个图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41569817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com