Nathalie
Nathalie

Reputation: 1238

Creating box plot into one plot

Having a dataframe like this

structure(list(google_before = c(0.26981640312419, 0.302252978236613, 
0.27519244423907, 0.278573602172958), amazon_before = c(0.165541492443112, 
0.162543532408399, 0.150484069110868, 0.212810080358854), ebay_before = c(0.698096408083222, 
0.625412783031095, 0.699099484936941, 0.610794910230257), yahoo_before = c(0.156164414439798, 
0.189265950612553, 0.151656203861282, 0.211930979296043), so_before = c(0.384820854982136, 
0.364443743167243, 0.352744936715994, 0.397252245652394), google_after = c(0.290892287578753, 
0.279948606399405, 0.262591995672118, 0.327138300630022), amazon_after = c(0.170072244074521, 
0.190821283262141, 0.136632592108377, 0.185400160041476), ebay_after = c(0.637122860008791, 
0.595805110056691, 0.713976579846045, 0.594306130039334), yahoo_after = c(0.154789410213351, 
0.185512865305938, 0.136271935262096, 0.18347290001916), so_after = c(0.359935532588727, 
0.391256325582968, 0.352913994612688, 0.312475345723399)), row.names = c(NA, 
-4L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x00000000003d1ef0>)

How is it possible to have one plot for all pairs of box plots: 1)google_before + before_after, 2) yahoo_before + yahoo_after etc.?

Upvotes: 1

Views: 29

Answers (1)

UseR10085
UseR10085

Reputation: 8188

You can use the following code

library(tidyverse)

df %>% 
  pivot_longer(everything()) %>% 
  ggplot(aes(x=name, y=value)) + geom_boxplot()

enter image description here

Update

library(stringr)

df1 = pivot_longer(df, everything())
df2 = cbind(df1,str_split_fixed(df1$name,"_",2))
colnames(df2)[3:4]=c("Company","Time")

ggplot(df2, aes(x=Company, y=value, fill=Time)) + geom_boxplot() + coord_flip()

enter image description here

Upvotes: 1

Related Questions