使用ggplot2中的不同x尺度和不同几何的两个数据帧进行图例控制 [英] Legend control with two data frames of different x-scales and different geoms in ggplot2

查看:280
本文介绍了使用ggplot2中的不同x尺度和不同几何的两个数据帧进行图例控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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




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.

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

解决方案

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

这篇关于使用ggplot2中的不同x尺度和不同几何的两个数据帧进行图例控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆