【问题标题】:R ggplot combine legends for colour and fill with different factor lengthR ggplot 结合了颜色的图例和填充不同的因子长度
【发布时间】:2019-03-04 18:09:18
【问题描述】:

我正在使用来自不完整因子设计的数据绘制图。由于设计的原因,我对颜色的手动刻度和填充的手动刻度有不同的长度。因此,我得到了两个传说。我怎样才能删除其中一个甚至更好地合并它们?

我看过这些问题:

Merge separate size and fill legends in ggplot

How to merge color, line style and shape legends in ggplot

How to combine scales for colour and size into one legend?

但是,答案对我没有帮助,因为它们没有处理不完整的设计。

这是一些示例数据和到目前为止我制作的图:

#Example data 
Man1 <- c(25,25,30,30,30,30,35,35,40,40,40,40,45,45) 
Man2 <- c(25,25,30,30,40,40,35,35,40,40,30,30,45,45) 
DV <- c(24.8,25.2,29.9,30.3,35.2,35.7,34,35.1,40.3,39.8,35.8,35.9,44,44.8)
Data <- data.frame(Man1,Man2,DV)

#Plot 
ggplot(data = Data, aes(x = Man1, y = DV, group=as.factor(Man2), colour=as.factor(Man2))) +
  theme_bw()  +  
  geom_abline(intercept = 0, slope = 1, linetype = "longdash") +  
  geom_point(position = position_dodge(1)) 
  geom_smooth(method = "lm", aes(x = Man1, y = DV, group=as.factor(Man2),   fill=as.factor(Man2)))  + 
  scale_colour_manual(name = "Man2", values=c('grey20', 'blue','grey20','tomato3', 'grey20'))  + 
  scale_fill_manual(name = "Man2", values=c('blue','tomato3'))

这给了我以下图片:

ggplot of incomplete design with two legends

有人可以给我一个提示,如何删除其中一个图例,或者更好地组合它们吗?我会很感激的!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    默认情况下,比例会降低未使用的因子水平,这与此处相关,因为只能获取您的几个组的行。

    您可以使用drop = FALSE 将其更改为适当的scale_*_manual()(此处用于fill)。

    然后对fillcolor 刻度使用相同的颜色向量。我通常为此制作一个命名向量。

    # Make vector of colors
    colors = c("25" = 'grey20', "30" = 'blue', "35" = 'grey20', "40" = 'tomato3', "45" = 'grey20')
    
    #Plot 
    ggplot(data = Data, aes(x = Man1, y = DV, group=as.factor(Man2), colour= as.factor(Man2))) +
        theme_bw()  +  
        geom_abline(intercept = 0, slope = 1, linetype = "longdash") +  
        geom_point(position = position_dodge(1))  +
    geom_smooth(method = "lm", aes(fill=as.factor(Man2)))  + 
        scale_colour_manual(name = "Man2", values = colors)  + 
        scale_fill_manual(name = "Man2", values = colors, drop = FALSE)
    

    或者,使用guide = "none" 一起删除fill 图例。

    ggplot(data = Data, aes(x = Man1, y = DV, group=as.factor(Man2), colour= as.factor(Man2))) +
        theme_bw()  +  
        geom_abline(intercept = 0, slope = 1, linetype = "longdash") +  
        geom_point(position = position_dodge(1))  +
        geom_smooth(method = "lm", aes(fill=as.factor(Man2)))  + 
        scale_colour_manual(name = "Man2", values = colors)  + 
        scale_fill_manual(name = "Man2", values=c('blue','tomato3'), guide = "none")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-17
      • 1970-01-01
      • 2020-10-03
      • 2022-11-22
      • 1970-01-01
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多