Reorder factor in MultiBarChart with NVD3 rCharts

爱⌒轻易说出口 提交于 2019-12-11 20:13:11

问题


Is there any way to reorder the factor as such Red,Black,Brown,Blond

require(rCharts)
hair_eye_male <- subset(as.data.frame(HairEyeColor), Sex == "Male")
n2 <- nPlot(Freq ~ Hair, group = 'Eye', data = hair_eye_male, type = 'multiBarChart')
n2

Thanks


回答1:


Reordering factors is an old art. Not to knock it...it's fun

In this context I'd revalue the data first. So if you wanted to have red,black,brown,blond appear in that order on the x axis...Add a new variable to your initial dataframe that maps hair color to how they should be ordered. The new variable should not be a factor. (red=1,black=2,brown=3,blond=4). I assume you've got that covered.

The code below just adds labels. Add this after n2 has been defined.

n2$xAxis(axisLabel = "Hair Color",tickValues=c("red","black","brown","blond"))



回答2:


You can set the factors in whichever order you want using the levels argument of factor(). Then if you reorder the dataframe according to those factors, the nPlot legend will be in the factor order you've specified.

hair_eye_male <- subset(as.data.frame(HairEyeColor), Sex == "Male")
hair_eye_male$Eye<-factor(hair_eye_male$Eye,levels=c('Green','Blue','Hazel','Brown'))
n<-nPlot(Freq~Hair,data=hair_eye_male[order(hair_eye_male$Eye),],group='Eye',type='multiBarChart')


来源:https://stackoverflow.com/questions/26402474/reorder-factor-in-multibarchart-with-nvd3-rcharts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!