Thomas Adler
Thomas Adler

Reputation: 47

How to change boxplots point color without overriding fill groups

I am trying to make boxplots that display three characteristic of the data (SiteID, Group, & TreatmentID). I am able to successfully represent two of the variables (SiteID and Group) as shown in the code below, but when I try to change the color of the points in the boxplot to represent my third characteristic (TreatmentID), it overrides the original grouping. Anybody have any idea how I could address this?

Here is my code:

myData <- structure(list(SiteID = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 1L, 1L, 2L, 2L, 3L, 3L), .Label = c("1", "2", "3"), class = "factor"), Group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Shale Hills", "Sleepers River"), class = "factor"),  TreatmentID = c("A", "R", "A", "R", "A", "R", "A", "R", "A", "R", "A", "R"), DOCmgkg = c(3.63, 6.43, 7.48, 10.04, 7.3, 8.2, 3.1, 8.1 ,6.36 , 1.8, 4.5, 5.4)), row.names = c("4", "8", "16", "20", "24", "28", "32", "36", "40", "44", "48", "52"), class = "data.frame")

# Bring in plot basics
library(ggplot2)
p<-ggplot(myData, aes(x=SiteID, y=DOCmgkg, fill=Group)) +
  geom_boxplot(position=position_dodge(1))

# Successful attempt at displaying two characteritics
p + geom_point(position=position_dodge(1), pch=21)

# Unsuccessful attempt at displaying three characteritics
p + geom_point(position=position_dodge(1), pch=21, aes(fill=factor(TreatmentID)))

Best, Thomas

Upvotes: 0

Views: 1109

Answers (2)

tim
tim

Reputation: 901

This gives your expected output with only a minor change, adding the group parameter to the geom_point aesthetics

p + geom_point(position=position_dodge(1),
               pch=21,
               aes(fill=factor(TreatmentID), group=Group))

enter image description here

Upvotes: 2

dc37
dc37

Reputation: 16178

I think you need to define a full aes for each plotting parameters (geom_boxplot and geom_point) and and remove aes from ggplot().

Also, you can use pch = 16 to get a full circle point filled with the same color than the border. Like that, you can replace aes(fill... by aes(color... avoiding you to pass twice fill in your plotting condition and you can use scale_color_manual to define colors only for points.

library(ggplot2)
ggplot(data = myData) +
  geom_boxplot(position=position_dodge(1), aes(x=SiteID, y=DOCmgkg, fill = Group)) + 
  geom_point(position=position_dodge(1), pch=16, aes(x = SiteID, y=DOCmgkg, group = Group, color =factor(TreatmentID)),size = 5)+
  scale_color_manual(values = c("green", "darkorange"))

enter image description here

Is it what you were looking for ?

Upvotes: 1

Related Questions