Reputation: 1
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.
Upvotes: 0
Views: 530
Reputation: 1
Although the solution provided by @Quinten worked for my dataset (visually), but somehow the summary of the boxplots (median, mean, etc) were not correct. So I searched some more and ended up using the pivot_longer function for my dataset.
df %>% select(X1, X2, X3, X4, X5) %>%
pivot_longer(., cols = c(X1, X2, X3, X4, X5),
names_to = "Var", values_to = "Val") %>%
ggplot(aes(x = Var, y = Val)) +
geom_boxplot()
This gave the correct distribution of my dataset (mean, medians etc.).
Upvotes: 0
Reputation: 41235
You can use the following code:
library(tidyverse)
library(reshape)
df %>%
melt() %>%
ggplot(aes(x = variable, y = value)) +
geom_boxplot() +
theme_bw()
Output:
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))
Upvotes: 1