Mathica
Mathica

Reputation: 1303

Remove part of Y axis in ggplot

I am trying to apply R/ggplot2: Collapse or remove segment of y-axis from scatter-plot to remove values from 25 to 75 from my plot's y axis. However i do not get the result desired when I have grouped plot.
what is the best way to squeeze part of y axis to make plots clear.

library(scales)
squish_trans <- function(from, to, factor) {
  
  trans <- function(x) {
    
    if (any(is.na(x))) return(x)

    # get indices for the relevant regions
    isq <- x > from & x < to
    ito <- x >= to
    
    # apply transformation
    x[isq] <- from + (x[isq] - from)/factor
    x[ito] <- from + (to - from)/factor + (x[ito] - to)
    
    return(x)
  }

  inv <- function(x) {
    
    if (any(is.na(x))) return(x)

    # get indices for the relevant regions
    isq <- x > from & x < from + (to - from)/factor
    ito <- x >= from + (to - from)/factor
    
    # apply transformation
    x[isq] <- from + (x[isq] - from) * factor
    x[ito] <- to + (x[ito] - (from + (to - from)/factor))
    
    return(x)
  }
  
  # return the transformation
  return(trans_new("squished", trans, inv))
}

df <- data.frame(state = factor(c("CA", "NY", "TX", "CA", "NY", "CA", "NY", "TX")),
                 value = c(2,5,4,8,9,7,4,6),
                 rangeL = c(1,4,3,7,8,5,3,5),
                 rangeU = c(4,7,5,9,10,9,100,70),
                 grp = factor(c("x", "x","x","y", "y","z","z","z")))
df

df %>%
    ggplot(aes(x=state, y= value, color = grp, group = grp)) +
    geom_point(position=position_dodge(.7)) +
    geom_errorbar(ymin = df$rangeL, ymax= df$rangeU, position=position_dodge(.7), width = 0.5) +
    expand_limits(x = 0, y = 0) +
    ylim(0, max(df$rangeU)) +
    scale_y_continuous(trans = squish_trans(25, 75, 10),
                     breaks = c(0, 5, 10, 20, 25, 75, 100))

enter image description here

Upvotes: 0

Views: 569

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

There's nothing wrong with your trans function. It's the way that you are using geom_errorbar that is problematic. Since, for some reason, you are not mapping the ymin and ymax aesthetics to the appropriate columns, but instead passing them as geom parameters outside of aes, they are not being used when calculating the correct range for the panel.

df %>%
  ggplot(aes(x=state, y= value, color = grp, group = grp)) +
  geom_point(position=position_dodge(.7)) +
  geom_errorbar(aes(ymin = rangeL, ymax= rangeU), 
                position=position_dodge(.7), width = 0.5) +
  scale_y_continuous(trans = squish_trans(25, 75, 10),
                     breaks = c(0, 5, 10, 20, 25, 75, 100))

enter image description here

Upvotes: 5

Related Questions