How to separate a legend to have it partly inside and outside the plot in ggplot?

Viewed 30

is there any possible way how to separate a legend in a plot? I want have it partly outside and inside the plot. I tried to separate legend which I wanted inside the plot by get_legend (cowplot library) and added as an object by inset_element from patchwork library...Unfortunately, I cannot customize it and need to inner legend with transparent backround.

This is the ggplot code which I am using at this moment:

ggplot() +
  geom_point(data = tot_grp, aes(x = soc_wat_m, y = obs_m, size = factor(n_group, levels = grp_n), fill = factor(group, levels = grp)), pch = 24) +
  geom_point(data = tot_grp, aes(x = soc_m, y = obs_m, size = factor(n_group, levels = grp_n), fill = factor(group, levels = grp)), pch = 21) +
  
  scale_fill_brewer(name = expression(paste("Classes [",m^-2,"·",yr^-58,"]")), 
                    palette = "PuOr") +
  scale_size_manual(name = "N per class", values = c(1, 2, 3, 4, 5, 6, 7)) +
  guides(fill = guide_legend(override.aes = list(shape = 21, size = 5), order = 2),
         color = guide_legend(override.aes = list(size = 5), order = 1),
         size = guide_legend(override.aes = list(shape = 21), order = 3)) +
  
  labs(x = expression(paste("SOC [kg·",m^-2, "]")),
       y = expression(paste("SOC [kg·",m^-2, "]"))) +
      
  coord_equal()+
  theme_bw()+
  theme(legend.position = "right"
        
  )+
  
  inset_element(p = legend_approach,
                right = 0.5,
                top = 0.55,
                left = 0.95,
                bottom = 0.95,
                clip = TRUE)

legend_approach is the object from get_legend function

Thank you!

1 Answers

I can't recreate your plot due to not having your data. You can try editing your legend position to a specific location

theme(legend.position = c(0.8, 0.2))

You can mess with the specific numbers

Related