Reputation: 223
I would like to create four boxplots next to each other with columnames on the x axis. I do not have much experience with boxplots in ggplot and I am uncertain how my data needs to be structured for getting the columnames with their related boxplots as factors on the x axis.
I am especially interested in how the y axis would be treated in this case.
col1<- c(0.43,0.78,-0.26,0.5,0.6,0.78,-0.2,0.1)
col2<- c(0.23,0.48,-0.76,0.1,0.9,0.73,-0.7,0.2)
col3<- c(0.83,0.18,-0.96,0.9,0.2,0.18,-0.79,0.3)
col4<- c(0.23,0.98,-0.16,0.4,0.3,0.49,-0.2,0.2)
test<-data.frame(col1,col2,col3,col4)
Upvotes: 0
Views: 101
Reputation: 42267
In ggplot2
, you want a "long", as opposed to wide data format. Full example:
library(ggplot2)
col1<- c(0.43,0.78,-0.26,0.5,0.6,0.78,-0.2,0.1)
col2<- c(0.23,0.48,-0.76,0.1,0.9,0.73,-0.7,0.2)
col3<- c(0.83,0.18,-0.96,0.9,0.2,0.18,-0.79,0.3)
col4<- c(0.23,0.98,-0.16,0.4,0.3,0.49,-0.2,0.2)
df <- rbind(
data.frame(name='col1', values=col1),
data.frame(name='col2', values=col2),
data.frame(name='col3', values=col3),
data.frame(name='col4', values=col4))
ggplot(df, aes(x=name, y=values)) + geom_boxplot()
Here df
represents the "long" format of data, where each measurement is on its own line.
Upvotes: 1
Reputation: 6685
You can reshape your data to long format using the melt()
function of the package reshape2
and then use the package ggplot2
to plot:
library(reshape2)
library(ggplot2)
col1<- c(0.43,0.78,-0.26,0.5,0.6,0.78,-0.2,0.1)
col2<- c(0.23,0.48,-0.76,0.1,0.9,0.73,-0.7,0.2)
col3<- c(0.83,0.18,-0.96,0.9,0.2,0.18,-0.79,0.3)
col4<- c(0.23,0.98,-0.16,0.4,0.3,0.49,-0.2,0.2)
test<-data.frame(col1,col2,col3,col4)
test2 <- melt(test)
ggplot(test2, aes(x = variable, y = value)) +
geom_boxplot()
Upvotes: 1