简体   繁体   中英

“error in axis” for Boxplot in R

I keep getting the following error:

Error in axis(side = 1, at = 1:3, labels = c("ADDA", "DM")) : 
  'at' and 'labels' lengths differ, 3 != 2

when running

boxplot(ELISA_Mussel$conc2~ELISA_Mussel$ELISA,main="ELISA",
    names=c("ADDA","DM"),
    ylab=expression(paste(mu,"g/L")))

although I only have 2 labels. Why does it say that I have 3? The data (ELISA_Mussel) looks like this:

ELISA   conc2
ADDA    20
ADDA    11.5
ADDA    18.5
ADDA    16.5
ADDA    17.6
ADDA    20
ADDA    11.5
ADDA    20
ADDA    14.5
ADDA    20
ADDA    8.5
ADDA    10.5
DM  6
DM  3.9
DM  4.3
DM  4.6
DM  5
DM  3.6
DM  6.2
DM  7
DM  3.8
DM  3.2
DM  5.4
DM  6.8
ADDA    8.6
ADDA    6.9
ADDA    3.9
ADDA    2.2
ADDA    7.4
ADDA    3.7
ADDA    4.5
ADDA    13.2
ADDA    8.6
ADDA    9.2
DM  1.6
DM  0.01
DM  0.01
DM  0.01
DM  0.01
DM  0.01
DM  0.01
DM  0.01
DM  1.6
DM  1.5

str(ELISA_Mussel)

'data.frame': 64 obs. of 15 variables:

$ ELISA : Factor w/ 3 levels "","ADDA","DM": 2 2 2 2 2 2 2 2 2 2 ... $ Seafood : Factor w/ 2 levels "","Mussel": 2 2 2 2 2 2 2 2 2 2 ... $ Method : Factor w/ 3 levels "","LongMeOH",..: 2 2 2 2 2 2 2 2 2 2 ... $ conc : Factor w/ 32 levels "","

You must have a factor with three levels, although only two are used. You can check by doing:

is.factor(ELISA_Mussel$ELISA)
# TRUE
nlevels(ELISA_Mussel$ELISA)
# [1] 3

You can fix that by dropping unused levels:

ELISA_Mussel$ELISA <- droplevels(ELISA_Mussel$ELISA)

Then it should plot fine.

In fact, you don't even have to modify your data if you use droplevels in the boxplot formula:

boxplot(ELISA_Mussel$conc2 ~ droplevels(ELISA_Mussel$ELISA),
        main="ELISA", ylab=expression(paste(mu,"g/L")))

(Also note that you can leave the names option alone since levels are used by default.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM