问题
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