0
votes

I am trying to plot a boxplot in R, where the input file has multiple columns and each column has different number of rows. With the help given on help on the following link:

boxplot of vectors with different length

I am trying:

x <- read.csv( 'filename.csv', header = T )
     plot(
       1, 1,
       xlim=c(1,ncol(x)), ylim=range(x[-1,], na.rm=TRUE), 
       xaxt='n', xlab='', ylab=''
       )
       axis(1, labels=colnames(x), at=1:ncol(x))

       for(i in 1:ncol(x)) {
       p <- x[,i]
       boxplot(p, add=T, at=i)
}

I am trying to plot the values in log scale. But defining log ="y", I am getting the following error:

Error in xypolygon(xx, yy, lty = "blank", col = boxfill[i]) : plot.new has not been called yet

Following is the sample of my input csv data:

A         B        C        D
2345.42   932.19   40.8     26.19
138.48    1074.1   4405.62  4077.16
849.35    0.0      1451.66  1637.39
451.38    146.22   4579.6   5133.14
5749.01   7250.08  12.23    0.09
4125.48   129.46   49.51
440.38    6405.02 
1
Please provide some data as well. - Roman Luštrik
Hi @Roli if my answer helped please consider accepting it (check mark to the left of the answer). This lets the community know that the answer worked and that it solved your issue. - CPak

1 Answers

3
votes

Your data as a reproducible example

Note I had to remove an extra element

library(data.table)
df <- fread("A,B,C,D
    2345.42,932.19,40.8,26.19
    138.48,1074.1,4405.62,4077.16
    849.35,0.0,1451.66,1637.39
    451.38,146.22,4579.6,5133.14
    5749.01,7250.08,12.23,0.09
    4125.48,129.46,49.51,440.38", sep=",", header=T)

dplyr and tidyr solution

library(dplyr)
library(tidyr)
df1 <- df %>% 
         replace(.==0,NA) %>%               # make 0 into NA
         gather(var,values,A:D) %>%         # convert from wide (4-col) to long (2-col) format
         mutate(values = log10(values))     # log10 transform

If you want log2, simply replace log10 with log2

Output

boxplot(values ~ var, df1)

A little extra

For log10 scale, I like to add 1 to my values to eliminate negative values since log10(0 < x < 1) = -value. This sets the minimum value on your plot as 0 since 0 + 1 = 1 and log10(1) = 0