2

我需要在我的两个图的顶部添加两条线(最佳拟合线和 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)
4

2 回答 2

7

这是另一种方法,它使用美学映射到字符串常量来识别不同的组并创建图例。

首先是创建测试数据的另一种方法(并将其命名DFnewdata

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("")

在此处输入图像描述

于 2013-10-03T22:35:13.137 回答
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. 在此处输入图像描述

于 2013-10-03T19:54:54.067 回答