r - Order Bars in ggplot2 bar graph -
i trying make bar graph largest bar nearest y axis , shortest bar furthest. kind of table have
name position 1 james goalkeeper 2 frank goalkeeper 3 jean defense 4 steve defense 5 john defense 6 tim striker
so trying build bar graph show number of players according position
p <- ggplot(thetable, aes(x = position)) + geom_bar(binwidth = 1)
but graph shows goalkeeper bar first defense, , striker one. want graph ordered defense bar closest y axis, goalkeeper one, , striker one. thanks
the key ordering set levels of factor in order want. ordered factor not required; information in ordered factor isn't necessary , if these data being used in statistical model, wrong parametrisation might result — polynomial contrasts aren't right nominal data such this.
## set levels in order want thetable <- within(thetable, position <- factor(position, levels=names(sort(table(position), decreasing=true)))) ## plot ggplot(thetable,aes(x=position))+geom_bar(binwidth=1)
in general sense, need set factor levels in desired order. there multiple ways of doing depending on situation. instance, do:
levels(thetable$position) <- c(...)
and list levels in desired order on right hand side. can specify level order within call factor above:
thetable$position <- factor(thetable$position, levels = c(...))
Comments
Post a Comment