簡體   English   中英

R lattice bwplot:根據因子水平填充具有特定顏色的箱形圖

[英]R lattice bwplot: Fill boxplots with specific color depending on factor level

我以此數據幀為例:

>mydata <- rbind(data.frame(Col1 = rnorm(2*1000),Col2 =rep(c("A", "C"), each=1000),Col3=factor(rep(c("YY","NN"), 1000))),data.frame(Col1 = rnorm(1000),Col2 =rep(c("B")),Col3=factor(rep(c("YY","YN"), 500))))

看起來像:

>head(mydata)
        Col1 Col2 Col3
1 -0.1213684    A   YY
2  0.1846364    A   NN
3  0.4028003    A   YY
4  1.4065677    A   NN
5 -0.8669333    A   YY
6  0.3295806    A   NN

因子類型的Col3有3個級別:NN YY YN

我想用格子bwplot制作一個箱線圖,並為每個級別分配一個特定的顏色:

# NN:
red=rgb(249/255, 21/255, 47/255)
# YN:
amber=rgb(255/255, 126/255, 0/255)
# YY:
green=rgb(39/255, 232/255, 51/255)

使用bwplot函數:

pl<-bwplot(mydata$Col1~mydata$Col3 | mydata$Col2,data=mydata,
ylab=expression(italic(R)),panel=function(...)
{panel.bwplot(...,groups=mydata$Col3, fill=c(red,amber,green))})

這導致如下圖: 例

顯然,顏色與我的數據框中的級別無關,因為YY框並不總是綠色。 有沒有辦法分配YY:綠色,NN:紅色和YN:琥珀色?

這是我要做的:

## Create a named vector of fill colors
red   <- rgb(249/255, 21/255, 47/255) # NN:
amber <- rgb(255/255, 126/255, 0/255) # YN:
green <- rgb(39/255, 232/255, 51/255) # YY:
fillCols <- c(NN=red, YN=amber, YY=green)

## Create a panel function that, with access to the subset of points plotted
## in the current panel, picks out the levels/colors that will be needed
myPanel.bwplot <- function(x=x, y=y, ...) {
    fill <- fillCols[intersect(levels(x), unique(x))] 
    panel.bwplot(x=x, y=y, ..., groups=Col3, fill=fill)
}

## Plot away
bwplot(Col1 ~ Col3 | Col2, data = mydata, panel = myPanel.bwplot)

在此輸入圖像描述

暫無
暫無

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

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