[R] Order axis by number of entries in lattice plot

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Mon Nov 4 15:25:05 CET 2019


On 04/11/2019 8:31 a.m., Luigi Marongiu wrote:
> Dear all,
> I am plotting some values with lattice barchart: the y-axis is
> automatically ordered alphabetically; is it possible to order the
> entries by number, so that the 'larger' histograms would be at the top
> of the plot?
> This is a working example
> 
> ```
> library(lattice)
> Family = c("Adenoviridae", "Baculoviridae",  "Herpesviridae",   "Mimiviridae",
> "Myoviridae", "Pandoraviridae",  "Phycodnaviridae", "Podoviridae",
> "Polydnaviridae",  "Retroviridae", "Siphoviridae",    "Unassigned")
> Normal = c(7, 15, 24,  8, 65, 24, 17, 16,  8, 15, 49 , 9)
> Tumour =c(  17,  75,  94,  14, 242,  28,  41,  69,  12,  11, 305,  51)
> Metastasis =c(41,  66,  95,   3, 173,  22,  33, 101,  12,  12, 552,  57)
> df = data.frame(Family, Normal, Tumour, Metastasis, stringsAsFactors = FALSE)
> COLS = c("darkolivegreen3", "brown3", "darkorchid3")
> barchart(Family ~ Normal+Tumour+Metastasis, data = df, stack = TRUE,
>           xlim=c(1,1000),
>           main = "Alphabetical order",
>           xlab = expression(bold("Number of species")),
>           ylab = expression(bold("Families")),
>           auto.key = list(space = "top", columns=3),
>           par.settings = list(superpose.polygon = list(col = COLS)))
> ```
> 
> 

You could do it by using an ordered factor.  For example,

o <- order(Normal + Tumour + Metastasis)
df$Ordered <- ordered(Family, levels = Family[o])
barchart(Ordered ~ Normal+Tumour+Metastasis, data = df, stack = TRUE,
          xlim=c(1,1000),
          main = "Ordered by total",
          xlab = expression(bold("Number of species")),
          ylab = expression(bold("Families")),
          auto.key = list(space = "top", columns=3),
          par.settings = list(superpose.polygon = list(col = COLS)))

Duncan Murdoch



More information about the R-help mailing list