0

我正在尝试为我的绘图上的每条回归线打印方程。这些方程相互重叠,因此只有一个方程是可见的。我想在一个独特的位置打印每个方程,这样它们就不会重叠。理想情况下,我希望它们都在下方、上方和旁边。

这是我的代码

library(ggplot2)
all_rates = read.csv("file.txt")
j=30

lm_eqn <- function(df){
        m <- lm(unlist(df[3]) ~ unlist(df[2]), df);
        eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
                list(a = format(coef(m)[1], digits = 2),
                        b = format(coef(m)[2], digits = 2),
                        r2 = format(summary(m)$r.squared, digits = 3)))
        as.character(as.expression(eq));
}

for(i in unique(gsub('_[0-9]+', '', all_rates[,1]))){
        rates <- all_rates[grep(i, all_rates[,1]),]
        freq = unlist(rates[2])
        temp = unlist(rates[3])
        exn = unlist(rates[4])
        p = ggplot(rates, aes(freq,temp)) + geom_point(data=rates, aes(freq,temp,group=exn,colour=exn)) + geom_smooth(data=rates, aes(freq,temp,group=exn,colour=exn),method = "lm",fill=NA) + geom_text(aes(x = 5, y = j), label = lm_eqn(rates), parse = TRUE, color = factor(exn), size=5) 
        ggsave(paste0(i, ".pdf"))
}

文件.txt

clothing,freq,temp,exon
coat_1,0.3,10,1
coat_1,0.9,0,1
coat_1,0.1,20,1
coat_2,0.5,20,2
coat_2,0.3,15,2
coat_2,0.1,5,2
scarf,0.4,30,1
scarf,0.2,20,1
scarf,0.1,10,1

更新

这是我更新的代码。我无法让颜色与线条的颜色相匹配,而且我无法摆脱文本中的一些凌乱字符,例如 ~ 和“

library(ggplot2)
all_rates = read.csv("file.txt")

lm_eqn <- function(df){
        m <- lm(unlist(df[3]) ~ unlist(df[2]), df);
        eq <- substitute(y == a + b * x*","~~r^2~"="~r2,
                list(a = format(coef(m)[1], digits = 2),
                        b = format(coef(m)[2], digits = 2),
                        r2 = format(summary(m)$r.squared, digits = 3)))
        as.character(as.expression(eq));
}

for(i in unique(gsub('_[0-9]+', '', all_rates[,1]))){
        rates <- all_rates[grep(i, all_rates[,1]),]
        num = 20 + length(unique(rates[,1])) - 1
        freq = unlist(rates[2])
        temp = unlist(rates[3])
        exn = unlist(rates[4])
        p = ggplot(rates, aes(freq,temp)) + geom_point(data=rates, aes(freq,temp,group=factor(exn),colour=factor(exn))) + geom_smooth(data=rates, aes(freq,temp,group=factor(exn),colour=factor(exn)),method = "lm",fill=NA)
        yval = 30
        for (k in unique(rates[,1])){
                sub_rates <- rates[rates[1] == toString(k),]
                p = p + annotate("text", x = 0.5, y = yval, label = lm_eqn(sub_rates), colour="red")
                yval = yval + 5
        }
        ggsave(paste0(i, ".pdf"))
}
4

0 回答 0