user3370708
user3370708

Reputation: 87

Multiple coloured box plots in R with legends

I have a raw data which looks like this: A B C D E F G H I J K L M N O P 1 15.0 20 23.3 26.5 28 29.0 31.8 32.0 32.0 33.8 36.0 38 40 46 47.0 55.0 2 10.0 13 16.0 20.0 10 19.5 14.0 15.0 31.0 15.0 24.6 29 31 46 26.7 38.2 3 18.0 25 29.5 45.0 47 36.5 41.0 38.0 34.5 63.0 43.0 41 42 55 55.0 78.0 4 32.5 60 108.7 88.0 83 65.9 84.9 125.1 62.6 83.0 71.6 53 55 72 88.3 123.8 5 22.0 36 65.0 63.0 60 43.8 53.0 74.0 44.3 71.0 50.3 44 46 62 63.5 96.0 6 10.0 NA NA NA 30 NA NA NA NA 20.0 NA NA NA NA NA NA 7 15.0 NA NA NA 25 NA NA NA NA NA NA NA NA NA NA NA 8 5.0 NA NA NA 40 NA NA NA NA 30.0 NA NA NA NA NA NA

These are actually the 2.5, 25, 50, 75 and 97.5 percentile values. I want to create box plots from these with different colours each and then mark the median point with a dot in the boxplot. I tried writing the following commands but got stuck with an error I could not comprehend.

Boxplot <- read.csv(file="Boxplots.csv",head=TRUE,sep=",")
Boxplot
attach(Boxplot)
boxplot(Boxplot, las = 2, col = c("sienna","royalblue2","chartreuse3","chartreuse4","chocolate","chocolate1","chocolate2","chocolate3","chocolate4","coral","coral1","coral2","coral3","coral4","cornflowerblue"), 
        at = c(1,2,3,4,5, 6,7,8,9, 10,11,12,13,14,15), par(mar = c(0, 5, 4, 2) + 0.1), 
        names = c("","","","","","","","","","","","","","",""))

Kindly help.

Upvotes: 3

Views: 541

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

I would (always) steer clear of attach. Especially here because you've already assigned Boxplot to your data, so it's already "attached". The error you're getting is likely due to the length of your col argument being longer than the number of columns.

> dat <- read.table(header = TRUE, text = "A       B       C       D       E       F       G
  15.0    20.0    23.3    26.5    28.0    29.0    31.8
  10.0    13.0    16.0    20.0    10.0    19.5    14.0
  18.0    25.0    29.5    45.0    47.0    36.5    41.0
  32.5    60.0    108.7   88.0    83.0    65.9    84.9
  22.0    36.0    65.0    63.0    60.0    43.8    53.0")

> boxplot(dat, col = rainbow(7), medlwd = 0)
> points(sapply(dat, median), pch = 19)

enter image description here

Upvotes: 1

Related Questions