0

I want to build ridgeline plot where each density corresponds to a different column (not a different group of the same column). Is there a way to do this in ggplot?

Marti
  • 67
  • 5
  • 1
    In general, ggplot2 and related packages are designed to work primarily with longer data, so I’d suggest pivoting your columns first. See tidyr’s pivot_longer and many questions on stack overflow if you search “[r] reshape wide to long” – Jon Spring Aug 29 '23 at 02:12

1 Answers1

0

By doing it I realised it does not make much sense unless you have variables with a similar domain. This is not true in the below solution and hence, while being correct, it produces an ugly plot.

library(ggridges)
library(ggplot2)
library(tidyr) 

# Sample data
data(diamonds)

diamonds$treat <- sample(c(0, 1), nrow(diamonds), replace = TRUE)
# Reshape the data
diamonds_long <- diamonds %>%
  pivot_longer(cols = c("carat", "depth", "price"), names_to = "variable")

ggplot(diamonds_long, aes(x = value, y = variable)) +
  geom_density_ridges()

For such cases, better to take a facet approach.

Marti
  • 67
  • 5