首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Forestplot -多变量和数据帧

Forestplot -多变量和数据帧
EN

Stack Overflow用户
提问于 2016-06-06 16:27:52
回答 1查看 483关注 0票数 1

我正在使用下面的代码来做forestplot。

它工作得很好,没有任何问题,但我想从两个数据帧中绘制森林图。因此,结果要么具有来自每个数据帧的变量,要么位于同一行,具有不同的颜色。

另外,->将变量的顺序改为Z-> A,我希望它们保持非字母顺序。

代码语言:javascript
复制
forestplot <- function(d, xlab="Estimate", ylab="Study"){
  require(ggplot2)
 p <- ggplot(d, aes(x=x, y=y, ymin=ylo, ymax=yhi)) + 
geom_pointrange() + 
coord_flip() +
geom_hline(yintercept=0, lty=3) +
ylab(xlab) +
xlab(ylab) + #switch because of the coord_flip() above
ggtitle("...")
return(p)
}    
forestplot(d)

结果应该是这样的(没有糟糕的编辑和多个变量):

EN

回答 1

Stack Overflow用户

发布于 2016-06-06 20:44:50

只需在函数开头绑定两个数据框即可:

代码语言:javascript
复制
 forestplot <- function(d1, d2, xlab="Estimate", ylab="Study")
   {
   d = rbind(cbind(d1, df = "1"), cbind(d2, df = "2"))
   require(ggplot2)
   p <- ggplot(d, aes(x=x, y=y, ymin=ylo, ymax=yhi, color = df, group = df)) + 
   geom_pointrange(position = position_dodge(width = 0.5)) + 
   coord_flip() +
   geom_hline(yintercept=0, lty=3) +
   ylab(xlab) +
   xlab(ylab) + #switch because of the coord_flip() above
   ggtitle("...")
   return(p)
 } 

代码语言:javascript
复制
 set.seed(1)
 d1 <- data.frame(y = runif(5), 
             x = sample(c("s1", "s2", "s3", "s4", "s5"), replace=F))
 d1$ylo = d1$y - runif(1)
 d1$yhi = d1$y + runif(1)

 d2 <- data.frame(y = runif(5), 
             x = sample(c("s1", "s2", "s3", "s4", "s5"), replace=F))
 d2$ylo = d2$y - runif(1)
 d2$yhi = d2$y + runif(1)

 forestplot(d1,d2)

编辑

代码语言:javascript
复制
 print(d1)
           y  x          ylo       yhi
 1 0.2655087 s5  0.059534088 0.4420654
 2 0.3721239 s4  0.166149325 0.5486807
 3 0.5728534 s2  0.366878788 0.7494101
 4 0.9082078 s3  0.702233215 1.0847645
 5 0.2016819 s1 -0.004292644 0.3782387

 print(d2)
           y  x         ylo       yhi
 1 0.6870228 s5  0.03534908 0.8125779
 2 0.3841037 s2 -0.26757005 0.5096588
 3 0.7698414 s3  0.11816765 0.8953965
 4 0.4976992 s4 -0.15397452 0.6232543
 5 0.7176185 s1  0.06594474 0.8431736

我无法使用此数据重现您的错误(注释),问题可能出在输入数据框中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37652761

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档