[R] Plotting Factors -- Sorting x-axis

Marc Schwartz mschwartz at medanalytics.com
Wed Apr 23 05:39:24 CEST 2003


>-----Original Message-----
>From: r-help-bounces at stat.math.ethz.ch 
>[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Ko-Kang 
>Kevin Wang
>Sent: Tuesday, April 22, 2003 9:57 PM
>To: R Help
>Subject: [R] Plotting Factors -- Sorting x-axis
>
>
>Hi,
>
>Say I have a factor with 20-levels: 1, 2, 3, ..., 20, called foo.
>
>If I do 
>  plot(foo)
>it will draw a barplot.  But the x-axis is sorted 
>alphanumerically, i.e. 
>1, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 2, 3, ..., 9, which 
>is not what 
>I want.  I'd like to x-axis to be in the order of 1 ~ 20 
>numerically.  So, 
>the question is, how do I change the order on the x-axis in this
case?
>
>-- 
>Cheers,
>
>Kevin


How about this:

# Create vector as you have with chars
# Note the factor level values
> x <- factor(as.character(1:20))
> x
 [1] 1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18
[19] 19 20
20 Levels: 1 10 11 12 13 14 15 16 17 18 19 2 20 3 4 ... 9

# Now sort factor levels by numeric value
# Note the factor level values
> x <- factor(x, levels = sort(as.numeric(x)))
> x
 [1] 1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16 17 18
[19] 19 20
20 Levels: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ... 20

Now plot(x).

Hope that helps.

Marc Schwartz



More information about the R-help mailing list