完美契合ggplot2绘图的情节

时间:2015-07-23 12:16:10

标签: r plot ggplot2 spline

我想绘制一个受限制的三次样条曲线作为主图,并添加一个盒子和须状图来显示X变量的变化。但是,下铰链(x = 42),中间(x = 51)和上铰链(x = 61)与主图的相应网格线不完全吻合。

library(Hmisc)
library(rms)
library(ggplot2)
library(gridExtra)

data(pbc)
d <- pbc
rm(pbc)
d$status <- ifelse(d$status != 0, 1, 0)

dd = datadist(d)
options(datadist='dd')

f <- cph(Surv(time, status) ~  rcs(age, 4), data=d)
p <- Predict(f, fun=exp)
df <- data.frame(age=p$age, yhat=p$yhat, lower=p$lower, upper=p$upper)

### 1st PLOT: main plot
(g <- ggplot(data=df, aes(x=age, y=yhat)) + geom_line(size=1))

# CI
(g <- g + geom_ribbon(data=df, aes(ymin=lower, ymax=upper), alpha=0.5, linetype=0, fill='#FFC000'))

# white background
(g <- g + theme_bw())

# X-axis
(breaks <- round(boxplot.stats(p[,"age"])$stats))
(g <- g + scale_x_continuous(breaks=breaks, limits=range(p[,"age"]), labels=round(breaks)))
(g <- g + xlab("Age"))

# Y-Achse
(g <- g + ylab("Hazard Ratio"))

# size and color of axis
(g <- g + theme(axis.line = element_line(color='black', size=1)))
(g <- g + theme(axis.ticks = element_line(color='black', size=1)))

(g <- g + theme( plot.background = element_blank() ))
#(g <- g + theme( panel.grid.major = element_blank() ))
(g <- g + theme( panel.grid.minor = element_blank() ))
(g <- g + theme( panel.border = element_blank() ))

### 2nd PLOT: box whisker plot
describe(df$age, digits=0)
round(range(df$age))
(gg <- ggplot(data=df, aes(x=1, y=age)) + geom_boxplot(outlier.shape=NA, size=1) + coord_flip())
(gg <- gg + theme( axis.line=element_blank() )) #
(gg <- gg + theme( axis.text.x=element_blank() ))
(gg <- gg + theme( axis.text.y=element_blank() ))
(gg <- gg + theme( axis.ticks=element_blank() ))
(gg <- gg + theme( axis.title.x=element_blank() ))
(gg <- gg + theme( axis.title.y=element_blank() ))
(gg <- gg + theme( panel.background=element_blank() ))
(gg <- gg + theme( panel.border=element_blank() )) #
(gg <- gg + theme( legend.position="none" )) #
(gg <- gg + theme( panel.grid.major=element_blank() )) #
(gg <- gg + theme( panel.grid.minor=element_blank() ))
(gg <- gg + theme( plot.background=element_blank() ))
(gg <- gg + theme( plot.margin = unit( c(0,0,0,0), "in" ) ))

(gg <- gg + scale_x_continuous(breaks=c(70,77,84), expand=c(0,0)) )

### FINAL PLOT: put box whisker plot in main plot
(final.gg <- g + annotation_custom(ggplotGrob(gg),  ymin=2.4, ymax=2.6))
  1. 为了完美契合,我需要改变什么?
  2. 是否有更好的自动对齐的y位置 盒和晶须?
  3. enter image description here

    更新#1 感谢您的回答!下面你可以看到我的代码示例。但是,如您所见,下铰链,中间和上铰链仍然不适合。出了什么问题?

    library(Hmisc)
    library(rms)
    library(ggplot2)
    library(gridExtra)
    
    data(pbc)
    d <- pbc
    rm(pbc, pbcseq)
    d$status <- ifelse(d$status != 0, 1, 0)
    
    dd = datadist(d)
    options(datadist='dd')
    
    f <- cph(Surv(time, status) ~  rcs(age, 4), data=d)
    p <- Predict(f, fun=exp)
    df <- data.frame(age=p$age, yhat=p$yhat, lower=p$lower, upper=p$upper)
    
    ### 1st PLOT: main plot
    (breaks <- boxplot.stats(p[,"age"])$stats)
    g <- ggplot(data=df, aes(x=age, y=yhat)) + geom_line(size=1) +
         geom_ribbon(data=df, aes(ymin=lower, ymax=upper), alpha=0.5, linetype=0, fill='#FFC000') +
         theme_bw() +
         scale_x_continuous(breaks=breaks) +
         xlab("Age") +
         ylab("Hazard Ratio") +
         theme(axis.line = element_line(color='black', size=1),
               axis.ticks = element_line(color='black', size=1),
               plot.background = element_blank(),
               # panel.border = element_blank(),
               panel.grid.minor = element_blank())
    
    ### 2nd PLOT: box whisker plot
    gg <- ggplot(data=df, aes(x=1, y=age)) + 
         geom_boxplot(outlier.shape=NA, size=1) + 
         scale_y_continuous(breaks=breaks) +
         ylab(NULL) +
         coord_flip()  + 
         # theme_bw() +
         theme(axis.line=element_blank(), 
               # axis.text.x=element_blank(),
               axis.text.y=element_blank(),
               axis.ticks.y=element_blank(), 
               axis.title=element_blank(),
               # panel.background=element_blank(),
               panel.border=element_blank(),
               # panel.grid.major=element_blank(),
               panel.grid.minor=element_blank(),
               # plot.background=element_blank(),
               plot.margin = unit( c(0,0,0,0), "in" ), 
               axis.ticks.margin = unit(0, "lines"),
               axis.ticks.length = unit(0, "cm"))
    
    ### FINAL PLOT: put box whisker plot in main plot
    (final.gg <- g + annotation_custom(ggplotGrob(gg),  ymin=2.4, ymax=2.6))
    

    enter image description here

2 个答案:

答案 0 :(得分:4)

次要编辑:更新到ggplot2 2.0.0 不推荐使用axis.ticks.margin

在箱线图中,即使您已将各种元素设置为element_blank且边距设置为零,默认空格仍然会导致未对齐。这些空间属于:

  • axis.ticks.length
  • xlab

在下面的代码中,我稍微重新安排了您的代码(我希望没问题),并注释掉了一些代码行,以便可以看出这两个图对齐。我还将两个图中的断点设置为非舍入breaks(最小值和最大值,铰链和中位数)。

# X-axis
(breaks <- boxplot.stats(p[,"age"])$stats)

### 1st PLOT: main plot
g <- ggplot(data=df, aes(x=age, y=yhat)) + geom_line(size=1) +
     geom_ribbon(data=df, aes(ymin=lower, ymax=upper), alpha=0.5, linetype=0, fill='#FFC000') +
     theme_bw() +
     scale_x_continuous(breaks=breaks) +
     xlab("Age") +
     ylab("Hazard Ratio") +
     theme(axis.line = element_line(color='black', size=1),
       axis.ticks = element_line(color='black', size=1),
       plot.background = element_blank(),
      # panel.border = element_blank(),
       panel.grid.minor = element_blank())

### 2nd PLOT: box whisker plot
gg <- ggplot(data=df, aes(x=1, y=age)) + 
      geom_boxplot(outlier.shape=NA, size=1) + 
      scale_y_continuous(breaks=breaks) +
      xlab(NULL) +
      coord_flip()  + 
     # theme_bw() +
      theme(axis.line=element_blank(), 
         # axis.text.x=element_blank(),
          axis.text.y=element_blank(),
          axis.ticks.y=element_blank(), 
          axis.title=element_blank(),
         # panel.background=element_blank(),
          panel.border=element_blank(),
         # panel.grid.major=element_blank(),
          panel.grid.minor=element_blank(),
         # plot.background=element_blank(),
          plot.margin = unit( c(0,0,0,0), "in" ), 
         # axis.ticks.margin = unit(0, "lines"),
          axis.ticks.length = unit(0, "cm"))

### FINAL PLOT: put box whisker plot in main plot
(final.gg <- g + annotation_custom(ggplotGrob(gg),  ymin=2.4, ymax=2.6))

enter image description here

您应该注意,ggplot计算铰链的方法与boxplot.stats使用的方法略有不同。

# ggplot's hinges
bp = ggplot(data=df, aes(x=1, y=age)) + 
      geom_boxplot(outlier.shape=NA, size=1)
bpData = ggplot_build(bp)
bpData$data[[1]][1:5]

答案 1 :(得分:3)

Alternative answer using var Array = ["Iphone", "겔럭시", "베가아이언"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. picker.delegate = self picker.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { return Array[row] } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return Array.count } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } @IBAction func buttonTapped(sender: AnyObject) { label.text = Array[row] ///this part error "use of unresolved identifier row" } functions to position the boxplot outside the main plot. The height of the box plot can be adjusted using the "h" parameter

gtable

enter image description here