簡體   English   中英

使用ggplot2和tablegrob繪制帶有NA值的多個矩陣的匯總統計量的分組箱圖

[英]Use ggplot2 and tablegrob to plot grouped boxplots with summary statistics from multiple matrices with NA values

我已經搜索了一段時間,但我仍然無法解決這個小問題,我想在tablegrob()創建的表中更改數字的小數位。 這樣做會使整個視圖看起來更好, 如下所示:

在此輸入圖像描述

這是代碼:

a<-as.vector(matrixA) #matrices A-D contain randomly generated NA and 
b<-as.vector(matrixB) #numerical values
c<-as.vector(matrixC)
d<-as.vector(matrixD)
data <- cbind(a, b, c, d)
plot <- melt(data)
colnames(plot)[2]<-"variable"
plot<-plot[,-1]
levels(df$variable) <- c("A", "B", "C",
                                  "D")
xlabs <- paste(levels(plot$variable),"\n(N=",
               colSums(!is.na(data)),")",sep="")
boxplot1<-ggplot(na.omit(plot),aes(x=variable,y=value,color=variable))+
  geom_boxplot()+scale_x_discrete(labels=xlabs)+
  xlab("X") + ylab("Y")+ 
  ggtitle("Title")
#create inset table
multi.fun <- function(x) {
  c(Mean = mean(x,na.rm=TRUE), Median = median(x,na.rm=TRUE), 
    IQR = IQR(x,na.rm=TRUE))}
sum.table<-data.frame(lapply(data.frame(a,b,c,d), multi.fun))
colnames(sum.table)<- c("A", "B", "C",
                        "D")
my_table <- tableGrob(sum.table, **digits=2**, gpar.coretext = gpar(fontsize=8), 
                      gpar.coltext=gpar(fontsize=8), gpar.rowtext=gpar(fontsize=8))
#Create the viewports, push them, draw and go up
grid.newpage()
vp1 <- viewport(width = 0.75, height = 1, x = 0.375, y = .5)
subvp <- viewport(width = 0.3, height = 0.3, x = 0.75, y = 0.20)
print(boxplot1, vp = vp1)
upViewport(0)
pushViewport(subvp)
grid.draw(my_table)

我嘗試使用tablegrob digits來調整值,這不起作用。 我也嘗試了選項(數字= 2) ,這也沒有用。 有什么想法或想法嗎?

colnames(sum.table)<- c("A", "B", "C","D")
***sum.table<-format(sum.table[1:3,1:4], digits=2)***
my_table <- tableGrob(sum.table, 
            gpar.coretext = gpar(fontsize=8), gpar.coltext=gpar(fontsize=8), 
            gpar.rowtext=gpar(fontsize=8))

在使用tableGrob使用sum.table<-format(sum.table[1:3,1:4], digits=2)之前格式化data.frame,我獲得了所需的結果:

在此輸入圖像描述

暫無
暫無

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

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