Anders
Anders

Reputation: 73

Five Boxplots in one ggplot

I want to make five boxplots of time series (data frame) in one ggplot. Is that possible?

This is how I've done so far, making one at a time and then I can have them side by side with plot_grid.

BoxAAPL <- ggplot(oldandnew, aes(y = oldandnew[,2])) + 
  geom_boxplot() +
  xlab("") + 
  ylab("Daily Return %") +
  theme_classic() 

But is it possible to have them all in one plot? That is for each of: "AAPL, not cleaned","AAPL, cleaned","GE","SPY","WMT"? From here http://www.sthda.com/english/wiki/ggplot2-box-plot-quick-start-guide-r-software-and-data-visualization I can see that I should change from numeric to factor but that doesn't really makes sense to me. Maybe because it's times series data?

A data sample:

structure(list(Date = structure(c(10960, 10961, 10962, 10963, 
10966), class = "Date"), `AAPL, not cleaned` = c(-8.810021, 1.45281, 
-9.051401, 4.628075, -1.774445), `AAPL, cleaned` = c(-8.810021, 
1.45281, -9.051401, 4.628075, -1.774445), GE = c(-4.08219945, 
-0.17376199, 1.32681098, 3.7986923, -0.03966156), SPY = c(-3.989133, 
0.1787311, -1.620197, 5.645238, 0.3424661), WMT = c(-3.813763, 
-2.360084, 1.391327, 7.280618, -1.841673)), row.names = c(NA, 
5L), class = "data.frame")

I hope you can help me out.

Upvotes: 0

Views: 73

Answers (1)

Ian Campbell
Ian Campbell

Reputation: 24888

This is easy to do with ggplot, but ggplot expects the data to have each observation on its own row of the data.frame.

This is the same approach recommended in one of the answers to one of your previous questions.

Therefore, we need to do some data transformation first. We can use pivot_longer from tidyr to do this, and we can use the -Date selection argument to tell it to pivot all columns except Date. The defaults move the names of the columns to the name column and the values to value.

Then we tell ggplot to group the values by name and change their colors in the aes call.

library(dplyr)
library(tidyr)
library(ggplot2)
oldandnew %>%
  pivot_longer(-Date) %>%
  ggplot(aes(y=value, x=name, fill=name)) +
     geom_boxplot() +
     xlab("") + 
     ylab("Daily Return %") +
     theme_classic() 

enter image description here

Upvotes: 1

Related Questions