簡體   English   中英

在刻面圖中用N注釋x軸

[英]Annotate x-axis with N in faceted plot

我正在嘗試制作一個按照治療條件和訪問次數分解的一些數字結果的箱線圖,每個框中的觀察數量放在該圖下,並且訪問數字也標記為。 這里有一些虛假的數據可以用來說明,我舉兩個例子,我試過的東西不太合適。

library(ggplot2)
library(plyr)

trt      <- factor(rep(LETTERS[1:2],150),ordered=TRUE)
vis      <- factor(c(rep(1,150),rep(2,100),rep(3,50)),ordered=TRUE)
val      <- rnorm(300)
data     <- data.frame(trt,vis,val)
data.sum <- ddply(data, .(vis, trt), summarise,
            N=length(na.omit(val)))
mytheme  <- theme_bw() + theme(panel.margin = unit(0, "lines"), strip.background = element_blank())

下面的代碼生成一個圖表,其中有我想要的N個標簽。 它通過從我創建的輔助數據集中獲取摘要數據來實現此目的。 但是,我無法弄清楚如何在x軸上標記訪問(理想情況下,在單個框標簽下面),或者以其他方式直觀地描繪訪問(例如,將它們分隔成面板的線條)。

plot1    <- ggplot(data) + 
            geom_boxplot(aes(x=vis:trt,y=val,group=vis:trt,colour=trt), show.legend=FALSE) +
            scale_x_discrete(labels=paste(data.sum$trt,data.sum$N,sep="\n")) +
            labs(x="Visit") + mytheme

下面的情節比上面的情節更接近我想要的,因為它有一個很好的治療和訪問層次結構,以及描繪訪問的漂亮格式。 但是,對於每個面板,它從與處理條件匹配的摘要數據中的第一行中獲取Ns,因為它不“知道”每個方面需要使用與該訪問相對應的行。

plot2    <- ggplot(data) +     geom_boxplot(aes(x=trt,y=val,group=trt,colour=trt), show.legend=FALSE) +
            facet_wrap(~ vis, drop=FALSE, switch="x", nrow=1) +
            scale_x_discrete(labels=paste(data.sum$trt,data.sum$N,sep="\n")) +
            labs(x="Visit") + mytheme

一種解決方法是操縱數據集,使x變量成為trtN之間的交互。

解決已有的問題,可以通過mergeN添加到原始數據集中。

test = merge(data, data.sum)

然后創建一個新變量,它是trtN的組合。

test = transform(test, trt2 = paste(trt, N, sep = "\n"))

現在使用x軸上的新trt2變量並使用scales = "free_x"facet_wrap以允許每個面的不同標簽。

ggplot(test) +     
    geom_boxplot(aes(x = trt2, y = val, group = trt, colour = trt), show.legend = FALSE) +
    facet_wrap(~ vis, drop = FALSE, switch="x", nrow = 1, scales = "free_x") +
    labs(x="Visit") + 
    mytheme 

在此輸入圖像描述

由於這個功能不是建立在一個良好的解決方案是grid.extra

library(gridExtra)
p1    <- ggplot(data[data$vis==1,]) +     geom_boxplot(aes(x=trt,y=val,group=trt,colour=trt), show.legend=FALSE) +
  #facet_wrap(~ vis, drop=FALSE, switch="x", nrow=1) +
  scale_x_discrete(labels=lb[1:2]) + #paste(data.sum$trt,data.sum$N,sep="\n")
  labs(x="Visit") + mytheme

p2    <- ggplot(data[data$vis==2,]) +     geom_boxplot(aes(x=trt,y=val,group=trt,colour=trt), show.legend=FALSE) +
  #facet_wrap(~ vis, drop=FALSE, switch="x", nrow=1) +
  scale_x_discrete(labels=lb[3:4]) + #paste(data.sum$trt,data.sum$N,sep="\n")
  labs(x="Visit") + mytheme

p3    <- ggplot(data[data$vis==3,]) +     geom_boxplot(aes(x=trt,y=val,group=trt,colour=trt), show.legend=FALSE) +
  #facet_wrap(~ vis, drop=FALSE, switch="x", nrow=1) +
  scale_x_discrete(labels=lb[5:6]) + #paste(data.sum$trt,data.sum$N,sep="\n")
  labs(x="Visit") + mytheme


grid.arrange(p1,p2,p3,nrow=1,ncol=3) # fully customizable

在此輸入圖像描述

相關: 在ggplot / R中每個面的不同軸標簽格式化器

您也可以將它們垂直或進行其他轉換:

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM