Sharif Amlani
Sharif Amlani

Reputation: 1278

How to make a boxplot with subset values and all values on the same plot?

I am working with base R plot.

I want to create a boxplot that includes both subset values and all values on the same plot. The key is it must be in base R plot.

Party <- rep(c("Rep", "Dem", "Ind"), 50)
Values <- sample(1:100, size = length(Party), replace = T)

hw <- data.frame(Party, Values)

#Plot 1
boxplot(hw$Values, 
        col=c("green"),
        xlab = "All Respondents")
#Plot 2
boxplot(hw$Values~hw$Party, 
        col=c("blue", "purple", "red"),
        xlab = "Partisan Respondents")


I essentially would like plot 1 and plot 2 to be combined into one plot.

Any help you could offer would be greatly appreciated. Thank You!

Upvotes: 1

Views: 121

Answers (1)

cuttlefish44
cuttlefish44

Reputation: 6786

It is simple way to add all values group.

library(dplyr)   # edited line

hw2 <- hw %>% 
  bind_rows(hw %>% mutate(Party = "ALL"))

boxplot(Values ~ Party, data = hw2,
        col = c("gray60", "blue", "purple", "red"),
        xlab = "Partisan Respondents")

Upvotes: 1

Related Questions