Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arbitrarily re-ordering histogram columns in R

I would like to know how I can re-order the columns of a histogram in a way that makes sense to my data. This example illustrates what I'm trying to do.

I have this data in a file:

blue    low
blue    medium
blue    high
blue    high
blue    high
blue    medium
green   low
green   low
green   low
green   high
pink    low
pink    high
pink    medium
pink    low
pink    high
red     high
red     low
red     low
red     low
red     medium
red     medium
red     medium

If I run these commands:

colours <- read.table("colours.txt", sep="\t")
library(lattice)
histogram(~ V2 | V1, data=colours,  type="count")

I get pretty much what I want except that the columns in the histograms are sorted alphabetically, high, low, medium and I would like to have them sorted in the more natural way low, medium, high.

Thanks very much in advance for any pointers on how to accomplish this.

like image 752
Alfredo Avatar asked Dec 02 '25 03:12

Alfredo


1 Answers

You just need to order your factors:

colours$V2 = factor(colours$V2, levels=c("low", "medium", "high"))
histogram(~ V2 | V1, data=colours,  type="count")
like image 151
csgillespie Avatar answered Dec 04 '25 07:12

csgillespie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!