在带有cowplot / ggplot2的空面板中绘制图例

时间:2017-01-10 13:36:07

标签: r ggplot2 cowplot

我有一个包含5个图和一个共享图例的面板,我想在(2行,3列)-grid中排列。右下方面板应用于图例。

            string[] result = renderHTML.Split('\n');
            string strInput = "";
            string strFinal = "";
            foreach (var item in result)
            {
                if (item.Contains("<input"))
                {
                    int indexOfSteam = item.IndexOf("<input");
                    strInput = item.Remove(0, indexOfSteam);
                    strInput = strInput.Replace("<td>", "");
                    strInput = strInput.Replace("</td>", "");
                    strFinal += strInput + "|";
                    strInput = "";
                }
            }
            string[] controls = strFinal.Split('|');

这遵循此处给出的教程: https://cran.r-project.org/web/packages/cowplot/vignettes/shared_legends.html

现在问题是,我在小插图中用最后一个情节命令修补了:

library(ggplot2)
library(cowplot)
df <-data.frame(a=seq(1,20),b=seq(1,20), c=as.factor(c(rep("A", 10),rep("B",10))))
O <- ggplot(df, aes(x = a, y = b)) + geom_point(aes(col=c))
legend <- get_legend(O)

A <- ggplot(df, aes(x = a, y = b)) + geom_point(aes(col=c), show.legend = F)
B <- ggplot(df, aes(x = c, y = b)) + geom_boxplot(aes(col=c), show.legend = F)
C <- ggplot(df, aes(x = a, y = b)) + geom_line(aes(group=c, col=c), show.legend=F)
D <- ggplot(df, aes(a)) + geom_histogram()



lol <- plot_grid(A, B, C,
                 D, A, NULL, ncol=3, nrow=2, 
                 align="hv", rel_widths = c(1, 1, 1, 1, 1, 1),
                 labels = c('A', 'B', 'C', 'D', 'E', ''))

但是我无法理解draw_grob参数中给出的(明显的?)坐标系的逻辑。有人可以澄清如何将图例导航到空白处吗?

注意,我不能在'plot_grid'中使用对象'legend',因为它会阻止对齐工作。

1 个答案:

答案 0 :(得分:1)

您需要将其视为一个矩形,点(xy)为左下角,右上角为(x +宽度{{1 }} {Ÿ{1}} height`)。

所以,在这种情况下:

,

enter image description here

请注意,您可能需要稍微增加+以使其与其他绘图的实际绘图区域保持一致,而不是整个画布。