[R] Ordering bars in barplots

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Jan 15 16:49:26 CET 2004


by() will sort on the levels of `class', so I think what you need to do is 
ensure that `class' has its levels sorted numerically.  Try

df$class <- factor(as.numeric(as.character(df$class)))

to do that.  Then to sort the df by numerical class you could use

df <- df[sort.list(unclass(df$class)), ]

It might be easier just to make class a number for some purposes at
least (just omit the factor() above).


On Thu, 15 Jan 2004, Scott Norton wrote:

> 
> I have a dataframe such that when I enter the dataframe name at the R prompt
> and see the data, the order of the data is correct (ie. what I want -
> ordered numerically by the factor, class).  The table is akin to the
> following:
> 
> df: (dataframe = df)
> uniqueID  class	age
> a	   1	32
> b	   1	21
> c	   1	13
> d	   1	11
> e	   3	15
> f	   3	16
> g	   3	31
> h	   3	25
> i	   4	23
> j	   4	32
> k	   4	31
> l	   7	11
> m	   7	6
> n	   7	20
> o	  10	19
> p	  10	25
> q	  10	42
> .
> .
> .
> 
> 
> uniqueID and class are factors. Yesterday I think I managed to figure out
> how to arrange the column "class" in "numerical" order (when it lists) even
> though it's a "character" factor.  (although feel free to pipe in an answer
> on that too - since I was trying a lot of different things!)
> 
> Now, when I execute the following command:
> 
> barplot(by(df[,"age"],df$class,FUN=function(x) quantile(x,0.95)))
> 
> the x-labels or "class" of each bar is in *character* order, not *numerical
> order.
> 
> Is there a way to rearrage this so that each bar label (categorical x-label)
> is in numerical order?
> 
> Thanks in advance!!!
> Best,
> Scott
> 
> 
> 
> 
> 
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
> 
> 

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list