Mike Dereviankin
Mike Dereviankin

Reputation: 71

How to jitter only one categorical variable

How do I retain one variable (a single point) to not be jittered while keeping the jitter on the other categorical variable in ggplot?

Here is the code I am currently using and what the output looks like:

# load ggplot2
library(ggplot2)
library(hrbrthemes)

# A basic scatterplot with color depending on Species
p <- ggplot(dt, aes(x=Type, y=y, color=Type)) + 
      geom_jitter(shape=22,
        alpha=0.5,
        size=2) +
     geom_hline(yintercept=c(1.4, 28.7, 2.65, 14.9)) +
     labs(y = 'ng/g lipid', title = 'PCB 99')
 
# Log base 10 scale
p + scale_y_continuous(trans = 'log10')

enter image description here

Upvotes: 0

Views: 1501

Answers (1)

stefan
stefan

Reputation: 125268

One option would be to split your data in categories (or (single) observations) which you want to be displayed jittered and not to be jittered. The first set of data could then be passed to geom_jitter while for the second you could use geom_point.

Using iris as example data:

library(ggplot2)

ggplot(iris, aes(x = Species, y = Sepal.Length, color = Species)) +
  geom_jitter(
    data = iris[!iris$Species == "setosa", ],
    shape = 22,
    alpha = 0.5,
    size = 2
  ) +
  geom_point(
    data = iris[iris$Species == "setosa", ],
    alpha = 0.5,
    size = 2
  )

Upvotes: 3

Related Questions