Search code examples
rggplot2plot

Trying to Differentiate lines in a Rain Cloud Plot


I have successfully created a raincloud plot using raincloudplots and the mtcars data set. Array 1 is the variable mpg and array 2 is qsec within each ID. I also created a variable $Direction which is 1 if mpg is bigger than qsec, and 2 if it is smaller. That way I can color the lines differently using this variable if they are in an upward or downward direction using an ifelse code. This variable is correct and I double checked it in excel, but the lines are not coloring accordingly. I have attached the code here, let me know if I can make this easier to understand in some capacity. Thanks!

Here's the plot Here's the data

library(raincloudplots) 

mtcars <- data_1x1(
  array_1 = mtcars$mpg,
  array_2 = mtcars$qsec,
  jit_distance = .09,
  jit_seed = 321)

head(mtcars)
tail(mtcars)

raincloud_2 <- raincloud_1x1_repmes(
  data = mtcars,
  colors = (c('#F6C337', '#68D2D5')),
  fills = (c('#F6C337', '#68D2D5')),
  line_alpha = .3,
  line_color= ifelse(mtcars$Direction > 1,  'black', 'gray'), 
  size = 1,
  alpha = .6,
  align_clouds = FALSE) +
  
  scale_x_continuous(breaks=c(1,2), labels=c("mpg", "qsec"), limits=c(0, 3)) +
  scale_y_continuous(breaks=c(1,5,10,15,20,25), limits=c(0, 25)) +
  ylab("Value") +
  xlab("")+
  theme_classic()

raincloud_2

Used

line_color= ifelse(mtcars$Direction > 1, 'black', 'gray')

Excpecting downward direction lines to be black but I got an assortment of colored lines.


Solution

  • I don't think there is an option to color the lines within the function itself. I think you'll need to modify the resulting ggplot object:

    library(raincloudplots) 
    library(tidyverse)
    
    mtcars <- data_1x1(
      array_1 = mtcars$mpg,
      array_2 = mtcars$qsec,
      jit_distance = .09,
      jit_seed = 321)
    
    raincloud_2 <- raincloud_1x1_repmes(
      data = mtcars,
      colors = (c('#F6C337', '#68D2D5')),
      fills = (c('#F6C337', '#68D2D5')),
      line_alpha = .3,
      size = 1,
      alpha = .6,
      align_clouds = FALSE) +
      scale_x_continuous(breaks=c(1,2), labels=c("mpg", "qsec"), limits=c(0, 3)) +
      scale_y_continuous(breaks=c(1,5,10,15,20,25), limits=c(0, 25)) +
      ylab("Value") +
      xlab("")+
      theme_classic()
    
    raincloud_2$data <- raincloud_2$data %>%
      mutate(Direction = ifelse(last(y_axis) - first(y_axis) > 0, "up", "down"),
                                .by = id)
    raincloud_2$layers[[3]]$aes_params$colour <- NULL
    raincloud_2$layers[[3]]$mapping <- aes(jit, y_axis, group = id, 
                                           color = Direction)
    
    raincloud_2 + scale_color_manual(values = c(up = "gray", down = "black"))
    

    enter image description here