【发布时间】:2023-04-11 01:54:01
【问题描述】:
我有一个不同属的测量数据集。其中一些属有多个数据点,其他属只有一个。我编写了以下代码来生成包含Measurement_A 和Measurement_B 的measurements 表的散点图。
# Load ggplot2 and ggpmisc
library(ggplot2)
library(ggpmisc)
measurements <- read.csv("measurements.csv")
# Define colours and shapes for each genus (which I've called A, B, C and D)
colour_specifications <- c("A"="green", "B"="red", "C"="yellow", "D"="blue")
shape_specifications <- c("A"=15, "B"=16, "C"=17, "D"=18)
# Create scatterplot of data from each genus
# and plot a regression line for each genus and show the R^2 value for each line
scatterplot <- ggplot(measurements, aes(x=Measurement_A, y=Measurement_B,
colour=Genus, shape=Genus))+
+ geom_point()+theme_classic()+
+ scale_color_manual(values = colour_specifications)+
+ scale_shape_manual(values= shape_specifications)+
+ geom_smooth(method=lm, se=FALSE)+
+ stat_poly_eq(formula = y ~ x, eq.with.lhs=FALSE, parse = TRUE)
> scatterplot
尽管属 C 和 D 只有一个数据点,但图例显示了回归线和符号。我想找到一种方法来为那些具有多个数据点的属子集(属 A 和 B)绘制回归线。我试过subset函数如下,
scatterplot <- ggplot(measurements, aes(x=Measurement_A, y=Measurement_B,
colour=Genus, shape=Genus))+
geom_point()+theme_classic()+
scale_color_manual(values = colour_specifications)+
scale_shape_manual(values= shape_specifications)+
geom_smooth(data=subset(measurements, Genus="A"),
method='lm', se=FALSE)+
geom_smooth(method=lm, se=FALSE)+
stat_poly_eq(formula = y ~ x, eq.with.lhs=FALSE, parse = TRUE)
但这对传说没有任何影响,这让我觉得我做错了什么。
有没有办法只为 A 属和 B 属而不是 C 和 D 属绘制回归线?
预计到达时间:
这是我为此使用的数据:
Genus <- c("A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "C", "D")
Specimen <- c("Aa","Ab","Ac","Ad","Ae","Af","Ag","Ah","Ba", "Bb", "Bc", "Bd", "Ca", "Da")
Measurement_A <- c(60, 80, 100, 105, 120, 130, 140, 95, 70, 80, 90, 100, 170, 55)
Measurement_B <- c(10, 15, 30, 30, 35, 40, 40, 27, 10, 17, 20, 27, 15, 5)
measurements <- data.frame(Genus, Specimen, Measurement_A, Measurement_B)
我想要做的就是用一个图例创建一个我的数据图,但 A 和 B 类显示回归线和 R^2 值。上面的两组代码都给了我一个图例,其中包含所有符号的回归线,而不仅仅是 A 和 B。正如我上面解释的,我尝试了 subset 函数,但它不会改变图例。当我尝试时
scatterplot <- ggplot(measurements, aes(x=Measurement_A, y=Measurement_B,
colour=Genus, shape=Genus))+
geom_point()+theme_classic()+
scale_color_manual(values = colour_specifications)+
scale_shape_manual(values= shape_specifications)+
geom_smooth(method=lm, se=FALSE)+
scale_color_manual(values = c("green","red"),limits = c("A","B"))+
stat_poly_eq(formula = y ~ x, eq.with.lhs=FALSE, parse = TRUE)
scatterplot
我收到一条错误消息说"Scale for 'colour' is already present. Adding another scale for 'colour', which will replace the existing scale",然后我得到两个图例,一个带有预设符号,但所有属均为黑色,另一个带有颜色,但只是 A 属和 B 属的圆形符号。
预计到达时间:
我找到了答案,我只需要在geom_smooth括号中添加show.legend=FALSE即可。
【问题讨论】:
标签: r ggplot2 regression