Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color only a specific boxplot among many using ggplot

Tags:

r

ggplot2

I would like to specify the color of one boxplot among many using ggplot.

For example, say I were using the Orthodont dataset that comes with the nlme package.

How would I specify that I would like the boxplot for males to be green?

> head(Orthodont)
Grouped Data: distance ~ age | Subject
  distance age Subject  Sex
1     26.0   8     M01 Male
2     25.0  10     M01 Male
3     29.0  12     M01 Male
4     31.0  14     M01 Male
5     21.5   8     M02 Male
6     22.5  10     M02 Male
> ggplot(data = Orthodont) + geom_boxplot(aes(x = factor(Sex), y = distance))

Thanks!

like image 833
goldisfine Avatar asked Apr 29 '26 10:04

goldisfine


1 Answers

If you have many levels of x variable (for example Subject) and you don't need to show colors in legend then you could plot over another boxplot layer only for one level with color you need.

ggplot(data = Orthodont) + geom_boxplot(aes(x = Subject, y = distance))+
      geom_boxplot(data=Orthodont[Orthodont$Subject=="M01",],
                        aes(x = Subject, y = distance),fill="green")

enter image description here

like image 192
Didzis Elferts Avatar answered May 01 '26 01:05

Didzis Elferts