0

reproducible example:

library(datasets)
library(tidyverse)

data(iris)

iris$facet <- "A"
A <- iris
iris$facet <- "B"
B <- iris

iris <- rbind(A,B)

iris %>% 
  ggplot(aes(x = Sepal.Width, y = Sepal.Length, color = Species))+
  geom_line()+
  facet_wrap(.~facet)+
  theme(legend.position = c(0.4,0.6))
  

I have been asked to make a plot where this same legend is positioned on top of each facet. So the same identical legend that I have put at c(0.4,0.6). I don't mind having to specify exact position for each time I have to repeat the label, but I can't make it work. The only suggestions I have is using the directlabels package to label the lines. But this is not acceptable to those making the decision. I know that the default is to show this only once for the entire plot, but we think it would make it easier to interpret if we show this once for every facet. I don't like using grid.arrange as I have seen suggested - this will make it difficult to align the facets and share y axis etc. (since in my actual figure the y-axis are different)

Just to put it in other words I want the same label shown in A facet shown in the B facet at the same time.

Jakn09ab
  • 179
  • 9
  • Does this question help you? https://stackoverflow.com/questions/14840542/place-a-legend-for-each-facet-wrap-grid-in-ggplot2 – Peter Jun 26 '20 at 07:12

1 Answers1

0

Are you looking for something like this? Using patchwork, and placing all plots in a list, you can use wrap_plots which is like facet_wrap for a list of plots.

Then using the & operator you can apply a theme to all facets, so they are the same.

Edit: based on more info, I also added a scaling option that would scale x and y for all facets the same.

library(tidyverse)
library(patchwork)

data(iris)

plot_list <- list()

plot_list[[1]] <- 
  iris %>% 
  mutate(fac = "A") %>% 
  ggplot(aes(x = Sepal.Width, y = Sepal.Length, color = Species))+
  geom_line()+
  facet_wrap(~fac)

plot_list[[2]] <- 
  iris %>% 
  mutate(fac = "b") %>% 
  ggplot(aes(x = Sepal.Width, y = Sepal.Length, color = Species))+
  geom_line()+
  facet_wrap(~fac)

wrap_plots(plot_list) &
  theme(legend.position = c(.85,.85)) &
  scale_y_continuous(limits = c(4, 8)) &
  scale_x_continuous(limits = c(2, 4.5))

Created on 2020-06-26 by the reprex package (v0.3.0)

  • No not exactly. Because as I understand what you have done, is to create the two plots and put them together, similar to the gridarrange approach. This creates two separate y-axis, and it is another version of the approach that I would like to avoid. – Jakn09ab Jun 26 '20 at 07:58
  • @Jakn09ab, I edited my answer. You can apply scaling to x and y that would affect all facets like this also. – Athanasia Mowinckel Jun 26 '20 at 08:07