0

I've created a GGally plot by group from one column of my data, however there is no legend to identify group names. How do I add a legend to the plot?

My code:

ggpairs(data[ ,c(2,5)],  mapping = ggplot2::aes(color = group), 
        upper = list(continuous = wrap("cor", size = 3)), 
        lower = list(combo = wrap(ggally_facethist, bins = 10)), 
        diag = list(continuous = wrap("densityDiag"), 
                    mapping = ggplot2::aes(fill = group, alpha = 0.1)),
        title="Data by Group") +
        theme(plot.title = element_text(hjust = 0.5)) +
        theme(text = element_text(size = 10),
        axis.text.x = element_text(angle = 90, hjust = 1))

My output: enter image description here Ideally I'd like to be able to move the legend around, if necessary, but a legend on the right side would be fine. I am also wondering whether it's possible to create a separate legend and save this to an object.

ryp
  • 37
  • 6

1 Answers1

0

Try this:

gg <-  ggpairs(data[ ,c(2,5)],  mapping = ggplot2::aes(color = group), 
    upper = list(continuous = wrap("cor", size = 3)), 
    lower = list(combo = wrap(ggally_facethist, bins = 10)), 
    diag = list(continuous = wrap("densityDiag"), 
                mapping = ggplot2::aes(fill = group, alpha = 0.1)),
    title="Data by Group") +
    theme(plot.title = element_text(hjust = 0.5)) +
    theme(text = element_text(size = 10),
    axis.text.x = element_text(angle = 90, hjust = 1))

then add

gg + theme(legend.position = "bottom")

or whatever position you would like it

An external legend can be added by following directions here: How to add an external legend to ggpairs()?

Jonni
  • 804
  • 5
  • 16