2013-10-03 166 views
2

我需要在我的兩個地塊的頂部添加兩條線(最適合線和45度線)的圖例。對不起,我不知道如何添加劇情!請請幫助我,我真的很感激它!如何添加兩條不同線R的ggplot圖例?

下面是一個例子

type=factor(rep(c("A","B","C"),5)) 
xvariable=seq(1,15) 
yvariable=2*xvariable+rnorm(15,0,2) 
newdata=data.frame(type,xvariable,yvariable) 
p = ggplot(newdata,aes(x=xvariable,y=yvariable)) 
p+geom_point(size=3)+ facet_wrap(~ type) + 
    geom_abline(intercept =0, slope =1,color="red",size=1)+ 
    stat_smooth(method="lm", se=FALSE,size=1) 

回答

1

試試這個:

# original data 
type <- factor(rep(c("A", "B", "C"), 5)) 
x <- 1:15 
y <- 2 * x + rnorm(15, 0, 2) 

df <- data.frame(type, x, y) 

# create a copy of original data, but set y = x 
# this data will be used for the one-to-one line 
df2 <- data.frame(type, x, y = x) 

# bind original and 'one-to-one data' together 
df3 <- rbind.data.frame(df, df2) 

# create a grouping variable to separate stat_smoothers based on original and one-to-one data 
df3$grp <- as.factor(rep(1:2, each = nrow(df))) 

# plot 
# use original data for points 
# use 'double data' for abline and one-to-one line, set colours by group 
ggplot(df, aes(x = x, y = y)) + 
    geom_point(size = 3) + 
    facet_wrap(~ type) + 
    stat_smooth(data = df3, aes(colour = grp), method = "lm", se = FALSE, size = 1) + 
    scale_colour_manual(values = c("red","blue"), 
         labels = c("abline", "one-to-one"), 
         name = "") + 
    theme(legend.position = "top") 

# If you rather want to stack the two keys in the legend you can add: 
# guide = guide_legend(direction = "vertical") 
#...as argument in scale_colour_manual 

請注意,此解決方案不會推斷你的數據範圍外的一到一條線,這似乎原來的geom_abline就是這種情況。 enter image description here

+0

謝謝你這麼這麼這麼這麼這麼多!!!!!你救了我的命! – user2844018

7

這裏是另一種方法,它使用審美映射字符串常量來識別不同的組並創建一個圖例。

首先創建您的測試數據的另一種方法(和其命名爲DF,而不是newdata

DF <- data.frame(type = factor(rep(c("A", "B", "C"), 5)), 
       xvariable = 1:15, 
       yvariable = 2 * (1:15) + rnorm(15, 0, 2)) 

現在ggplot代碼。請注意,對於geom_ablinestat_smoothcolour都在內部設置,並且aes調用,這意味着所使用的兩個值中的每一個都將映射到不同的顏色,並且將爲該映射創建指南(圖例)。

ggplot(DF, aes(x = xvariable, y = yvariable)) + 
    geom_point(size = 3) + 
    geom_abline(aes(colour="one-to-one"), intercept =0, slope = 1, size = 1) + 
    stat_smooth(aes(colour="best fit"), method = "lm", se = FALSE, size = 1) + 
    facet_wrap(~ type) + 
    scale_colour_discrete("") 

enter image description here

+1

比我的嘗試更乾淨,+1!我應該學習的'ggplot'中有很多automagics ... – Henrik

+1

第一次遇到審美映射到字符串常量。確實有用! – Henrik

+0

@Henrik當審美被映射到一個字符串常量時,它通常是用戶部分的錯誤,因爲其意圖是設置而不是映射審美。但是這裏的映射真的是需要的。 –

相關問題