Home > Blockchain >  Plot boxplot for multiple numerical categories
Plot boxplot for multiple numerical categories

Time:05-03

I have a dataframe containing n columns. I would like to plot my data using boxplots for each element (X1, X2, X3,...X14). I am not able to figure out how to use my dataframe for multiple categories.

X1 X2 X3 X4 X4
0.867 0.568 0.674 0.976 0.332
0.546 0.532 0.653 0.994 0.848
0.546 0.532 0.653 0.994 0.848
0.546 0.532 0.653 0.994 0.848
0.546 0.532 0.653 0.994 0.848

I found one example with which I tried the following, but it is not working.

df <- data.frame(Xs = 1:14)
df <- melt(df , id.vars = 'Xs', variable_name = 'elements')

Test <- ggplot(df, aes(Xs, value))   geom_boxplot()

Any help would be appreciated! Thanks.

CodePudding user response:

You can use the following code:

library(tidyverse)
library(reshape)
df %>%
  melt() %>%
  ggplot(aes(x = variable, y = value))  
  geom_boxplot()  
  theme_bw()

Output:

enter image description here

Generated random data:

df <- data.frame(X1 = runif(14, 0, 1),
                 X2 = runif(14, 0, 1),
                 X3 = runif(14, 0, 1),
                 X4 = runif(14, 0, 1),
                 X5 = runif(14, 0, 1),
                 X6 = runif(14, 0, 1),
                 X7 = runif(14, 0, 1),
                 X8 = runif(14, 0, 1),
                 X9 = runif(14, 0, 1),
                 X10 = runif(14, 0, 1),
                 X11 = runif(14, 0, 1),
                 X12 = runif(14, 0, 1),
                 X13 = runif(14, 0, 1),
                 X14 = runif(14, 0, 1))

CodePudding user response:

Use facet_wrap. Also, use mutate to add the variable Xs to the data frame.

df <- tibble::tribble(
    ~X1,   ~X2,   ~X3,   ~X4,   ~X5,
  0.867, 0.568, 0.674, 0.976, 0.332,
  0.546, 0.532, 0.653, 0.994, 0.848,
  0.546, 0.532, 0.653, 0.994, 0.848,
  0.546, 0.532, 0.653, 0.994, 0.848,
  0.546, 0.532, 0.653, 0.994, 0.848
  )

df <- df %>% 
  mutate(Xs = 1:5) %>% 
  melt(id.vars = 'Xs')

ggplot(df, aes(Xs, value))   
  geom_boxplot()  
  facet_wrap(~ variable)

enter image description here

  • Related