将散点图与R中残差的旋转直方图相结合

时间:2018-01-03 23:49:14

标签: r ggplot2

考虑这样的数据集:

x=jitter(seq(1,100,1), amount = 8)
y=2*x+rnorm(length(x),mean =20,sd=10)
df=data.frame(x,y)
lm_xy=lm(data=df,y~x)

我想创建一个带有回归线的散点图,并插入残差的直方图(使用lm_xy)旋转,以匹配回归线的斜率。

情节必须如下:

Regression with inset histogram of residuals

取自here。我知道它可以通过网格包中的视口完成,但在尝试之后我无法完成。拜托,你能给我一个提示,让它在R的ggplot2中制作吗?

修改

这是我能做的最好的事情:

x=jitter(seq(1,100,1), amount = 8)
y=2*x+rnorm(length(x),mean =20,sd=10)
df=data.frame(x,y)
lm_xy=lm(data=df,y~x)
#get angle with 'deg' function from lm_xy
deg = function(rad) {
  return((180 * rad) / pi)
}


angle_sp=deg(atan(lm_xy$coefficients[2]))

res_xy=hist(lm_xy$residuals,breaks = 20)
res_xy=data.frame(breaks=res_xy$breaks[-1],counts=res_xy$counts)


resp=ggplot(h,aes(x,y))+geom_bar(stat = "identity", 
                                 color="black",fill="grey",size=1)+
  annotate(geom="segment", x = 0, xend = 0, y = -4, yend = max(h$y)+4,
           colour = "blue",size=1)+
  scale_x_continuous(breaks = seq(-10,10,20))+
  theme(
    panel.background = element_blank(),
    plot.margin = margin(0, 0, 2, 0, "cm"),
    axis.line=element_blank(),
    axis.text.y=element_blank(),
    axis.ticks = element_line(size=1,margin(0,0,0,0)),
    axis.text.x = element_text(margin = margin(-0.5,0,2,0, "cm")),
    axis.title.x=element_blank(),
    axis.title.y=element_blank(),
    panel.border = element_blank(),
    plot.background = element_rect(fill = "transparent",colour = NA)
  )

pdf("plot.pdf")
grid.newpage() 
plot(df$x,df$y)
abline(b=lm_xy$coefficients[2],a = lm_xy$coefficients[1])
pushViewport(viewport(x=.13,y=.81,width=.21,height=.24,just=c("left","top")))

grid.roundrect()
popViewport()
pushViewport(viewport(x=.3,y=0.85,angle=-63.6,width=.2,height=.35,just=c("left","top"))) 
par(plt = gridPLT(), new=TRUE)
print(resp,newpage = F)

dev.off()

这是输出:

enter image description here

1 个答案:

答案 0 :(得分:1)

这需要进行一些调整才能移动f grob,但我认为这会让你更接近。

来自here

library(tidyverse)

f <- ggplot(diamonds, aes(carat)) +
  geom_histogram()

ggplot(mtcars, aes(wt, mpg)) + geom_point()
print(f, vp = grid::viewport(width = 0.5, height=0.5, angle = -45))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> Warning in grid.Call.graphics(L_setviewport, vp, TRUE): cannot clip to
#> rotated viewport

#> Warning in grid.Call.graphics(L_setviewport, vp, TRUE): cannot clip to
#> rotated viewport

reprex package(v0.1.1.9000)于2018-01-04创建。