通过使用facet_wrap将r平方成ggplot

我刚刚加入社区,并希望能为我的硕士论文的数据分析提供帮助。

此刻我有以下问题:

我使用facet_wrap用ggplot绘制了42个变种:

`ggplot(sumfvvar,aes(x=TemperaturCmean,y=Fv.Fm,col=treatment))+
  geom_point(shape=1,size=1)+
  geom_smooth(method=lm)+
  scale_color_brewer(palette = "Set1")+
  facet_wrap(.~Variety)`

效果很好,但是我想为回归线标注r平方值。我有两种处理方式和42个变体,因此有84条回归线。 是否有可能计算所有r平方值并将其集成到ggplot中?我已经找到了功能

ggplotRegression <- function (fit) {

require(ggplot2)

ggplot(fit$model,aes_string(x = names(fit$model)[2],y = names(fit$model)[1])) + 
geom_point() +
stat_smooth(method = "lm") +
labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared,5),"Intercept =",signif(fit$coef[[1]],5 )," Slope =",signif(fit$coef[[2]]," P =",signif(summary(fit)$coef[2,4],5)))
}

但这仅适用于一种变种和一种处理。可能是lm()函数的循环选项吗?

zzp521cq 回答:通过使用facet_wrap将r平方成ggplot

除非将另一个r ^ 2列添加到数据中,否则不能将不同的标签应用于不同的方面。一种方法是使用geom_text,但需要首先计算所需的统计信息。下面我以虹膜为例,对于您的情况,只需更改Species for Variety等,

library(tidyverse)
# simulate data for 2 treatments
# d2 is just shifted up from d1
d1 <- data.frame(iris,Treatment="A")
d2 <- data.frame(iris,Treatment="B") %>% 
mutate(Sepal.Length=Sepal.Length+rnorm(nrow(iris),1,0.5))
# combine datasets
DF <- rbind(d1,d2) %>% rename(Variety = Species)

# plot like you did
# note I use "free" scales,if scales very different between Species
# your facet plots will be squished
g <- ggplot(DF,aes(x=Sepal.Width,y=Sepal.Length,col=Treatment))+
  geom_point(shape=1,size=1)+
  geom_smooth(method=lm)+
  scale_color_brewer(palette = "Set1")+
  facet_wrap(.~Variety,scales="free")

# rsq function
RSQ = function(y,x){signif(summary(lm(y ~ x))$adj.r.squared,3)}
#calculate rsq for variety + treatment
STATS <- DF %>%
group_by(Variety,Treatment) %>% 
summarise(Rsq=RSQ(Sepal.Length,Sepal.Width)) %>%
# make a label
# one other option is to use stringr::str_wrap in geom_text
mutate(Label=paste("Treat",Treatment,",Rsq=",Rsq))

# set vertical position of rsq
VJUST = ifelse(STATS$Treatment=="A",1.5,3)
# finally the plot function
g + geom_text(data=STATS,aes(x=-Inf,y=+Inf,label=Label),hjust = -0.1,vjust = VJUST,size=3)

对于最后一个geom_text()调用,我通过乘以“处理”来允许文本的y坐标不同。.您可能需要根据您的图进行调整。.

enter image description here

,

以下是import numpy as np from matplotlib import pyplot as plt def plot_polynomials(solutions,train_x,train_y): x = np.arange(-5,6) plt.plot(x,genPoly(x,solutions)) plt.show() data = read_coords("data.csv") data = np.asarray(data) system,solution = pol_regression(data[:,0],data[:,1],2) plot_polynomials(solution,1]) #I want to do something like this but im not sure what plot_polynomials() should contain #to be able to "hold onto" the constructed graph before showing. #I need all polynomials on the same graph for i in range(11): system,i) plot_polynomials(solution,1]) 包的示例:

ggpmisc

enter image description here

本文链接:https://www.f2er.com/3110816.html

大家都在问