Replacing a single box with dots and changing the order of boxes on multiple boxplot in R

2978 views r
5

I am new to R and looking to make a few adjustments to a side by side box plot I made in R. Below is some simplified code.

name <- c('a','a','a','a','a','a','a','a','a','a','b','b','b','b','c','c','c','c','c','c','c','c','c','c')
category <- c('y','y','y','y','y','x','x','x','x','x','x','y','x','y','x','x','x','x','x','y','y','y','y','y')
value <- c(10,20,30,40,50,60,70,80,90,100,40,50,60,70,10,20,30,40,50,60,70,80,90,100)

graphA <- data.frame(name, category, value)

ggplot(graphA, aes(x=name, y=value, fill = category))+
  geom_boxplot(width = 0.5, position=position_dodge(0.75))+
  scale_fill_grey(start = 0.8, end = 0.5) 

enter image description here

Which looks great. But I want to reverse the order of the categories so that the 'y' category is plotted first. I tried running this line of code:

graphA$category <- factor(graphA$category, values = c('y','x'))

But I get an error that reads

"Error in factor(graphA$category, values = c("y", "x")) : unused argument (values = c("y", "x"))"

I would also like to replace boxes for category b with two sets of colored dots because for that category I do not have enough points to call it a data distribution.

Any guidance you can provide is greatly appreciated!

answered question

It should be factor(graphA$categories, levels = c("y", "x")) (note the levels argument),

1 Answer

6

First, you need the levels argument in factor

graphA$category <- factor(graphA$category, levels = c('y','x'))

And here is a way you could plot category "b" as points. fill will only have an effect for shapes 21 to 25 in geom_point.

ggplot(subset(graphA, name != "b"), aes(x = name, y = value, fill = category)) +
  geom_boxplot(width = 0.5, position = position_dodge(0.75)) +
  geom_point(
    data = subset(graphA, name == "b"),
    size = 4,
    shape = 21,
    position = position_dodge(width = .4)
  ) +
  scale_fill_grey(start = 0.8, end = 0.5)

enter image description here

posted this

Have an answer?

JD

Please login first before posting an answer.