Shanqiao Chen
Shanqiao Chen

Reputation: 101

How to add a pseudo aesthetic argument to ggplot2 geom?

What I have and what I want:

data<- data.frame(value= 1:10, Treatment= rep(c("A", "B"),5), Species=rep(c("alpha", "beta"), each=5))

And it is known to all that ggplot2::aes() function can automatically group the data according to the arguments it quotes, for example, ggplot(data=data)+geom_boxplot(aes(y= value, x= Treatment, fill=Treatment)) separates and groups data by Treatment plot1

and is plotted as 2 different boxes. In like manner ggplot(data=data)+geom_boxplot(aes(y= value, x= Treatment, fill=Treatment, linetype= Species)) will generate 4 boxes grouped by both Teatment and Species with different color filling and linetype respectively plot2.

However, how to generate a boxplot of 4 boxes grouped by Treatment and Species in which Treatment is presented by filling color same as the plot metioned above, but Species was not presented, that is, the linetype is all the same among boxes? In other words, is there a null aesthetic only group the data but never be presented on the plot.

Upvotes: 0

Views: 162

Answers (3)

Shanqiao Chen
Shanqiao Chen

Reputation: 101

Combining the solutions of J Hart and baptiste, ggplot(data=data)+geom_boxplot(aes(y= value, x= Treatment, fill=Treatment, group= paste(Treatment, Species))) works perfectly.

Upvotes: 1

J Hart
J Hart

Reputation: 89

You can define a new variable that has 4 levels either in your data or on the fly as I have shown below. With this you will get the 4 box plots, colored and grouped as you asked for. No matter what you will probably need to distinguish the data in some way, either on the axis labels or in the legend.

ggplot(data=data)+geom_boxplot(aes(y= value, x= Treatment, fill=Treatment, group=paste(Species, Treatment))

enter image description here

Upvotes: 1

Prradep
Prradep

Reputation: 5696

You mean this?

ggplot(data=data)+
  geom_boxplot(aes(y= value, x= Treatment, fill=Treatment)) + 
  facet_wrap(~Species)

enter image description here

Upvotes: 1

Related Questions