Ale*_*own 9 color-scheme r ggplot2
对于在图表中具有超过合理数量级别的因子,我想用"其他"替换不在"前10"中的任何级别.
替代问题:如何将我的因子水平降低到rcolorbrewer可以绘制为单独颜色的数字?
例如,如果我想从棒球数据中绘制每十年的本垒打数:
require(ggplot2)
qplot(data=baseball,10*year%/%10,hr,
stat="identity",geom="bar")
Run Code Online (Sandbox Code Playgroud)

也许我想看看哪些团队为此做出了贡献:
qplot(data=baseball,10*year%/%10,hr,
fill=team,
stat="identity",geom="bar")
Run Code Online (Sandbox Code Playgroud)

这会产生太多的色彩等级!颜色是如此相似,你无法区分它们,并且有很多它们不适合屏幕.
我真的很想看到顶级的X(7)队(按总的本垒打数)然后其余的都集中在一个类别/颜色叫做"其他".
让我们假设我们有一个hotfactor知道如何执行此操作的函数:
hotfactor(afactor,orderby,count)={ ??? }
qplot(data=baseball,10*year%/%10,hr,
fill=hotfactor(factor(team),hr,n=7),
stat="identity",geom="bar") +
scale_fill_brewer("team","Dark2")
Run Code Online (Sandbox Code Playgroud)

那么我可以将什么用于'hotfactor'?
经过几次迭代并搜索网页后,我创建了这个很好的短文.
hotfactor= function(fac,by,n=10,o="other") {
levels(fac)[rank(-xtabs(by~fac))[levels(fac)]>n] <- o
fac
}
Run Code Online (Sandbox Code Playgroud)
它非常适合汇总数据,您可以使用它来访问伟大的rcolorbrewer颜色方案(每个颜色方案都有有限数量的精心挑选的颜色).
使用说明:
fac应该是一个因素,并且在没有空因子水平的情况下效果最佳.您可能想先跑droplevels(as.factor(mydata)).
它没有对因子水平进行排序.为了获得最佳的条形图结果,您应该在输出因子上运行以下内容.
x <- hotfactor(f,val)
x <- reorder(x,-val,sum)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1493 次 |
| 最近记录: |