本文介绍了如何绘制与水平平行的条形图到箱形图中具有面积比例的箱形图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行数据表示,因此需要并行绘制带堆叠barplot的boxplot。

I am working on data presentation and i need to plot boxplot with stacked barplot in parallel.

具有不同阴影颜色的着色,点覆盖面积的比例。我该如何绘制?

With colored in different shade colors with proportion of points covering area. How can i plot it?

推荐答案

这里是一个通用解决方案,可用于将平行百分比框添加到晶格弓形图中。它计算出箱形图部分(晶须和主体部分)的准确百分比。

Here a generic solution that you can use to add parallel percent box to a lattice bowplot. It computes the exact percent descrbing parts of boxplot (whisker and main part).

该解决方案基于网格包。使用晶格进行视口操作比使用ggplot2更容易,这就是为什么我选择bwplot。

The solution is based on the grid package. Viewport manipulation is easier with lattice than ggplot2, that's why I choose a bwplot.

我生成一些示例数据:

df <- data.frame(cond = factor( rep(c("A"), each=200) ),
                 rating = c(rnorm(200),rnorm(200, mean=.8)))

library(lattice)
bwplot(cond ~ rating, data=df,gp=gpar(fill='blue'),
       par.settings = list( box.umbrella=list(col= c( "red")),
                            box.dot=list(col= c("green")),
                            box.rectangle = list(fill= c( "blue"),alpha=0.6)))

I捕获主视口

downViewport("plot_01.panel.1.1.vp")

然后我存储晶须的尺寸和四边形的箱形图位置。

Then I store the dimensions of whiskers and positions of extremities boxplot positions.

segs <- grid.get('segments',grep=T)
cap.segs <- grid.get('cap.segments',grep=T)

f unction drawBox,用百分比绘制文本的矩形。我每个盒子叫3次。

The function drawBox , draw a rectangle with the text in percent. I Call it 3 times for each box.

drawbox <- function(x0 = segs$x0[1] , col ='red',
                    width.vp = segs$x0[2] - segs$x0[1]){
  vpd <- viewport(
            x = x0 ,
            y = cap.segs$y1[2] + unit(0.5,'native'),
            width  = width.vp,
            height = unit(2,'cm'),
            just   = c('left','bottom'),
            name   = 'vpd')
  pushViewport(vpd)
    grid.rect(gp=(gpar(fill=col)))
    # The compute of percent is a little bit tricky due we can't apply '/'
    value <- as.numeric(convertUnit(width.vp,'native'))
    value <- value/as.numeric(convertUnit(cap.segs$x0[2]- cap.segs$x0[1],'native'))
    grid.text(label = paste(round(value*100),'%',sep='') , gp= gpar(cex=3))
  upViewport(1)
}

函数提取框被调用3次:

The function drawbox is called 3 times:

drawbox()
drawbox(col='yellow',width=segs$x0[1] - cap.segs$x0[1], x0= cap.segs$x0[1])
drawbox(col='green',width.vp= cap.segs$x0[2]- segs$x0[2],x0 = segs$x0[2])

这篇关于如何绘制与水平平行的条形图到箱形图中具有面积比例的箱形图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-02 07:00