yuw444
yuw444

Reputation: 426

Additional color layer for geom_density_ridges()

I found below example:

library(ggplot2)
library(ggridges)

ggplot(iris, aes(x = Sepal.Length, y = Species)) +
  geom_density_ridges(
    jittered_points = TRUE,
    position = position_points_jitter(width = 0.05, height = 0),
    point_shape = '|', point_size = 3, point_alpha = 1, alpha = 0.7,
  )

iris$cat <- factor(sample(1:5, size = nrow(iris), replace = TRUE))

In my application, I have an additional category, cat besides Species. Is there any way to distinguish the below rug by cat using colors?

I tried aes(points_color = cat), but the result is undesired.

Please help.

Upvotes: 1

Views: 151

Answers (1)

Cullen.Molitor
Cullen.Molitor

Reputation: 417

This should do the trick

library(ggplot2)
library(ggridges)

iris$cat <- factor(sample(1:5, size = nrow(iris), replace = TRUE))

ggplot() +
  geom_density_ridges(
    data = iris, aes(x = Sepal.Length, y = Species), alpha = 0.7) +
  geom_density_ridges(
    data = iris, aes(x = Sepal.Length, y = Species, point_color = cat),
    jittered_points = TRUE, linetype = 0,
    position = position_points_jitter(width = 0.05, height = 0),
    point_shape = '|', point_size = 3, point_alpha = 1, alpha = 0
  )  +
  scale_color_viridis_d(aesthetics = "point_color")
  # scale_discrete_manual(aesthetics = "point_color",
  #                       values = c('black', 'red', 'grey', 'purple', 'blue'))

I put in two different ways to select the color values, just commented out the manual way.

enter image description here

Upvotes: 2

Related Questions