2
votes

Could someone explain to me on how to get full control over the legends in ggplot2 with two data frames with different x-scales presented in two different geoms. The 'name1' and 'name2' is a function that are created with other filtering function.

This is the plot1. Why geom_point shape appears in the legend for "Group 1"? I expect the legend will show only colour in Group1 and shape for Group2.

Is it possible to rearrange the legends as well? i.e Group2 appears first in the row.

df1 <- data.frame(g1 = c("a", "b", "c", "e"),
                  y1 = c(12, 8, 3, 20))
df2 <- data.frame(g1 = letters[1:5],
                  y1 = 20:24)
name1 <- "Group 1"
name2 <- "Group 2"

require(ggplot2)
ggplot(NULL, aes(x=g1, y=y1)) +
    geom_bar(data = df1, stat = "identity",
             aes(fill=factor(name1))) +
    geom_point(data = df2, stat = "identity",
               size = 5, shape = 2, aes(fill=factor(name2))) +
    theme(plot.margin = unit(c(2,1,1,1), "lines"),
                     plot.title = element_text(hjust = 0, size=18),
                     axis.title = element_text(face = "bold", size = 12),
                     legend.position = 'top',
                     legend.text = element_text(size = 12),
                     legend.title = element_blank())
1

1 Answers

0
votes

The key is to define fill and shape in both aes(). You can then define the shape and fill as NA for the one you don't need.

ggplot(NULL, aes(x=g1, y=y1)) +
  geom_bar(data = df1, stat = "identity", aes(fill=name2, shape=name2)) +
  geom_point(data = df2, size = 5, aes(shape=name1, fill=name1)) +
  theme(plot.margin = unit(c(2,1,1,1), "lines"),
        plot.title = element_text(hjust = 0, size=18),
        axis.title = element_text(face = "bold", size = 12),
        legend.position = 'top',
        legend.text = element_text(size = 12),
        legend.title = element_blank()) +
  scale_shape_manual(values=c(2, NA)) +
  scale_fill_manual(values=c(NA, "red")) +
  guides(fill = guide_legend(reverse = TRUE),
         shape = guide_legend(reverse = TRUE))

enter image description here