如何添加两条不同线R的ggplot图例?

问题描述 投票:0回答: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)
r ggplot2 legend
2个回答
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_abline
stat_smooth
colour
是在内部设置的,并且
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
投票

试试这个:

# 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

© www.soinside.com 2019 - 2024. All rights reserved.