【问题标题】:Legend control with two data frames of different x-scales and different geoms in ggplot2ggplot2中具有不同x尺度和不同几何图形的两个数据框的图例控制
【发布时间】:2016-05-06 22:48:01
【问题描述】:

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

1。 为什么 geom_point 形状出现在“第 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())

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    关键是在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))
    

    【讨论】:

      猜你喜欢
      • 2015-12-14
      • 2021-11-26
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      • 2021-11-05
      • 1970-01-01
      相关资源
      最近更新 更多