如何添加两个不同行R的ggplot图例?

时间:2013-10-03 18:59:33

标签: r ggplot2 legend

我需要在我的两个地块的顶部添加两条线(最佳拟合线和45度线)的图例。对不起,我不知道如何添加情节!请帮助我,我真的很感激!!!!

这是一个例子

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)

2 个答案:

答案 0 :(得分: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)

试试这个:

# 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