ChenKang
ChenKang

Reputation: 91

how to split the boxplot and jitter plot in left and right

I plotted the boxplot and jitter in ggplot, but they overlapped. I want to split them with the box-plot in left and jitter in right, position=position_nudge() doesn't work, how to do?

library(ggplot2)
ggplot(iris)+
  geom_boxplot(aes(Species,Sepal.Width,fill=Species),width=0.2)+
  geom_jitter(aes(Species,Sepal.Width,color=Species),width=0.2)

Upvotes: 0

Views: 489

Answers (1)

stefan
stefan

Reputation: 125697

One option to achieve your desired result would be to convert Species to a numeric and make use of a continuous scale like so:

library(ggplot2)

dodge_width <- .2
ggplot(iris) +
  geom_boxplot(aes(as.numeric(factor(Species)) - dodge_width, Sepal.Width, fill = Species), width = .2) +
  geom_jitter(aes(as.numeric(factor(Species)) + dodge_width, Sepal.Width, color = Species), 
              position = position_jitter(width = .1)) +
  scale_x_continuous(breaks = unique(as.numeric(factor(iris$Species))), labels = unique(factor(iris$Species)))

Upvotes: 1

Related Questions