R ggplot结合了图例的颜色和不同因子长度的填充

时间:2018-09-28 17:54:37

标签: r ggplot2

我正在使用不完整的析因设计中的数据进行绘图。由于设计原因,我的颜色的手动刻度和填充的手动刻度的长度不同。因此,我得到了两个传说。我如何删除其中之一,甚至更好地结合它们?

我看了那些问题:

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?

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

以下是一些示例数据以及我到目前为止生成的图:

invalidate

这给了我以下图片:

ggplot of incomplete design with two legends

有人可以提示我如何删除其中一个图例,甚至更好地将它们组合在一起吗?我将不胜感激!

1 个答案:

答案 0 :(得分:0)

默认情况下,标尺会降低未使用的因子水平,这在此处很重要,因为只能获得几个组的线。

您可以使用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)

enter image description here 或者,使用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")

enter image description here

相关问题