2017-12-18 298 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