我有一些R课程的数据。教授正在使用基本图形手动添加每一行。我想用ggplot2
来做。
到目前为止,我已在不同地区facet
ggplot
scatter plots
hunger
创建了一个x
'd图,并且还为数据单独拟合了一个模型。特定模型在图中的group/colour
变量与geom_abline
变量之间具有交互项。
我现在要做的是绘制每个面板为该模型生成的线。我可以使用slope
并将intercept
和stat_smooth
定义为2个系数的总和(因为组的分类变量具有0/1值,并且在每个面板中)只有一些值乘以1) - 但这似乎并不容易。
我尝试使用stat_smooth
中我在lm中使用的相同方程式而没有运气,我收到错误。
理想情况下,我认为可以将等式以某种方式放入ggplot
并让download.file("https://sparkpublic.s3.amazonaws.com/dataanalysis/hunger.csv",
"hunger.csv", method = "curl")
hunger <- read.csv("hunger.csv")
hunger <- hunger[hunger$Sex!="Both sexes",]
hunger_small <- hunger[hunger$WHO.region!="WHO Non Members",c(5,6,8)]
q<- qplot(x = Year, y = Numeric, data = hunger_small,
color = WHO.region) + theme(legend.position = "bottom")
q <- q + facet_grid(.~WHO.region)+guides(col=guide_legend(nrow=2))
q
# I could add the standard lm line from stat_smooth, but I dont want that
# q <- q + geom_smooth(method="lm",se=F)
#I want to add the line(s) from the lm fit below, it is really one line per panel
lmRegion <- lm(hunger$Numeric ~ hunger$Year + hunger$WHO.region +
hunger$Year *hunger$WHO.region)
# I also used a loop to do it, as below, but all in one panel
# I am not able to do that
# with facets, I used a function I found to get the colors
ggplotColours <- function(n=6, h=c(0, 360) +15) {
if ((diff(h)%%360) < 1) h[2] <- h[2] - 360/n
hcl(h = (seq(h[1], h[2], length = n)), c = 100, l = 65)
}
n <- length(levels(hunger_small$WHO.region))
q <- qplot(x = Year, y = Numeric, data = hunger_small,
color = WHO.region) + theme(legend.position = "bottom")
q <- q + geom_abline(intercept = lmRegion$coefficients[1],
slope = lmRegion$coefficients[2], color = ggplotColours(n=n)[1])
for (i in 2:n) {
q <- q + geom_abline(intercept = lmRegion$coefficients[1] +
lmRegion$coefficients[1+i], slope = lmRegion$coefficients[2] +
lmRegion$coefficients[7+i], color = ggplotColours(n=n)[i])
}
完成所有工作。怎么会这样呢?
{{1}}
答案 0 :(得分:0)
如果您有一个分类数据:
geom_point()
不起作用,
geom_boxplot()
会奏效。
ggplot(hunger, aes(x = sex, y = hunger)) + geom_boxplot() + labs(x="sex") + geom_smooth(method = "lm",se=FALSE, col = "blue"). Susy