Ggplot2 - Several boxes from sources of different lengths

I have several different variable length vectors for which I would like to create side by side using ggplot2. This is relatively straightforward for a base build system. However, ggplot2 uses only one data frame, which is difficult to create from data of various lengths.

a <- rnorm(10) b <- rnorm(100) c <- rnorm(1000) boxplot(a, b, c) 

Q: What is the correct way to draw boxes using ggplot2 using data of various lengths?


+6
source share
1 answer

ggplot uses neat long data frames with groups (e.g. a, b or c) stored as separate columns. In your example, you can create a data frame with 1110 rows (10 + 100 + 1000) and two columns (value and group), for example:

 # Make individual data frames a <- data.frame(group = "a", value = rnorm(10)) b <- data.frame(group = "b", value = rnorm(100)) c <- data.frame(group = "c", value = rnorm(1000)) # Combine into one long data frame plot.data <- rbind(a, b, c) # group value # 1 a 0.2322682 # 2 a -0.9681992 # ... # 101 b 0.3422354 # 102 b 0.3495342 # ... # 1001 c -0.6839231 # 1002 c -1.4329843 # Plot library(ggplot2) ggplot(plot.data, aes(x=group, y=value, fill=group)) + geom_boxplot() 

Example boxplot

+11
source

Source: https://habr.com/ru/post/978160/


All Articles