2017-12-18 294 views
0

我想用图例自动在ggplot中以灰色显示背景数据。我的目标是要么在图例中包含灰色数据点,要么用手动标题制作第二个图例。但是我没有做到这两者中的任何一个。我的数据格式很长。为多个数据集创建ggplot2图例

require(ggplot2) 

xx<-data.frame(observation="all cats",x=1:2,y=1:2) 
yy<-data.frame(observation=c("red cats","blue cats"),x=3:4,y=3:4) 

g<-ggplot() + 
    geom_point(aes(x,y, colour=factor(observation)), colour="grey60", size=5, data=xx) + 
    geom_point(aes(x,y, colour=factor(observation)), size=5, data=yy) + 
    scale_color_discrete(name = "ltitle") 

g 

enter image description here

我试图用rbind.data.frame,这产生了很好的传说合并data.frames,但当时我没能在颜色灰色的背景资料,并保持ggplot颜色在同一时间。

我也意识到,这解决了这个问题:

g<-ggplot(aes(x,y, colour=factor(observation)), colour="grey60", data=xx) + 
    geom_point(size=5) + 
    geom_point(aes(x,y, colour=factor(observation)), size=5, data=yy) + 
    scale_color_discrete(name = "ltitle") 
g 

但我不能这样做,因为我使用它之前创建一个复杂的空情节的功能,我在其中再加入geom_points

回答

0

假设你的阴谋没有需要填充参数等geoms,以下是修复您的后台数据的颜色geom_point层,而不会影响其他geom_point层的解决方法:

g <- ggplot() + 
    geom_point(aes(x, y, 
       fill = "label"),        # key change 1 
      shape = 21,          # key change 2 
      color = "grey50", size = 5, 
      data = xx) + 
    geom_point(aes(x, y, colour = factor(observation)), size = 5, data = yy) + 
    scale_color_discrete(name = "ltitle") + 
    scale_fill_manual(name = "", values = c("label" = "grey50")) # key change 3 
g 

shape = 21给你的形状看起来像默认的圆点,但接受除了颜色参数填充参数。然后,您可以设置XX的geom_point层的填充在scale_fill_manual()为灰色(这将创建一个填充图例),同时留下color = "grey50"aes()(不添加到颜色图例)。

yy's geom_point图层的色标不受此任何因素的影响。

plot

p.s.刚刚意识到我使用“grey50”而不是“grey60”......但其他一切仍然适用。 :)

0

一种解决方案是创建颜色矢量并将其传递到scale_color_manual

xx <- data.frame(observation = "all cats",x = 1:2,y = 1:2) 
yy <- data.frame(observation = c("red cats", "blue cats"),x = 3:4,y = 3:4) 
# rbind both datasets 
# OP tried to use rbind.data.frame here 
plotData <- rbind(xx, yy) 

# Create color vector 
library(RColorBrewer) 
# Extract 3 colors from brewer Set1 palette 
colorData <- brewer.pal(length(unique(plotData$observation)), "Set1") 
# Replace first color first wanted grey 
colorData[1] <- "grey60" 

# Plot data 
library(ggplot2) 
ggplot(plotData, aes(x, y, colour = observation)) + 
    geom_point(size = 5)+ 
    scale_color_manual(values = colorData, name = "ltitle") 

                                                                          enter image description here

0

我想出了几乎相同的溶液Z.Lin但将组合数据帧从rbind.data.frame。类似地,它使用与scale_colour_manual指定该颜色映射向量colors

require(ggplot2) 

xx<-data.frame(observation="all cats",x=1:2,y=1:2) 
yy<-data.frame(observation=c("red cats","blue cats"),x=3:4,y=3:4) 

zz <- rbind.data.frame(xx,yy) 

colors <- c(
    "all cats" = "grey60", 
    "red cats" = "red", 
    "blue cats" = "blue" 
) 

g<-ggplot() + 
    geom_point(aes(x,y, colour=factor(observation)), size=5, data=zz) + 
    scale_color_manual(values= colors, name = "ltitle") 
g 

enter image description here