ggplot2中具有不同x尺度和不同geoms的两个数据框的图例控件

Legend control with two data frames of different x-scales and different geoms in ggplot2

有人可以向我解释如何使用两个数据框完全控制 ggplot2 中的图例,两个数据框在两个不同的几何图形中呈现不同的 x 尺度。 'name1' 和 'name2' 是与其他过滤函数一起创建的函数。

1。 为什么 geom_point 形状出现在 "Group 1" 的图例中?我希望图例在 Group1 中仅显示颜色,在 Group2 中显示形状。

是否也可以重新排列图例?即 Group2 排在第一位。

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())

关键是在aes()中定义fillshape。然后您可以将 shapefill 定义为 NA 作为您不需要的那个。

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))