построить несколько сюжетов с легендами из других сюжетов рядом - PullRequest
0 голосов
/ 31 мая 2018

У меня есть три сюжета p1, p2 и p3.Я хотел бы объединить p2 и p3 и добавить легенды p2 и p1 с правой стороны друг над другом.В следующем примере легенды идентичны.В реальных данных они различны.

Я использую ggplot2 и cowplot

# plot 1
p1 <- ggplot(iris, aes(Sepal.Length, fill = Species)) +
  geom_density(alpha = .7) 


# plot 2
p2 <- ggplot(iris, aes(Sepal.Width, fill = Species)) +
  geom_density(alpha = .7)

# plot 3
p3 <- ggplot(iris, aes(Petal.Width, fill = Species)) +
  geom_density(alpha = .7)


# legend1

legend1 <- get_legend(p1)

# legend2

legend2 <- get_legend(p2)

# combine plots
prow <- plot_grid( p2 + theme(legend.position="none"),
                   p3 + theme(legend.position="none"),
                   align = 'vh',

                   labels = c("a", "b"),

                   hjust = -1,

                   nrow = 1,
                   axis="1"

)

prow

# add legend1
p <- plot_grid( prow, legend1, rel_widths = c(1, .3))
p
# add legend2
plot_grid(p, legend2, rel_widths =c(1, .3))

Это дает мне это: Result

Я пытаюсь получить: Wish

Я пытался решить проблему, используя

+ theme(legend.position=c()

и

+ theme(legend.justification = "top"))

однако я не смог получить желаемый сюжет.

1 Ответ

0 голосов
/ 31 мая 2018

Ты на самом деле очень близко.Вы можете использовать ggdraw для достижения того, что вы хотите.См. ?get_legend для другого примера этого.

# combine plots
prow <- ggdraw(
  plot_grid(
    plot_grid(p2 + theme(legend.position="none") ,
               p3 +theme(legend.position="none"),
               align = 'vh',

               labels = c("a", "b"),

               hjust = -1,

               nrow = 1,
               axis="1"),
# as suggested by aosmith you can add additional columns to make legends appear closer
    plot_grid(legend1, legend2,ncol=4),
# I also set the relative widths so the legend takes up less space
nrow=1, rel_widths = c(1,0.2))
  )

prow

enter image description here

...