gpt4 book ai didi

R 格子 bwplot : Fill boxplots with specific color depending on factor level

转载 作者:行者123 更新时间:2023-12-05 01:00:12 26 4
gpt4 key购买 nike

我以这个数据框为例:

>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

作为具有 3 个级别的因子类型的 Col3: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))})

结果如下图:
Example

显然颜色与我的数据框中的级别无关,因为 YY 框并不总是绿色。有没有办法分配 YY:green、NN:red 和 YN:amber?

最佳答案

这是我要做的:

## 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)

enter image description here

关于R 格子 bwplot : Fill boxplots with specific color depending on factor level,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29802129/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com