Carolina Karoullas
Carolina Karoullas

Reputation: 406

How to crop a line when it's above a certain value without affecting other lines in R using ggplot2?

I'm trying to create a graph in R using the ggplot2 package. I can make the graph without any issues as per the simplified example below:

library(tidyverse)

A <- c(10,9,8,7,6,5,4,3,2,1,2,3,4,5,6,7,8,9,10)
B <- c(15,14,13,12,11,10,9,8,7,6,7,8,9,10,11,12,13,14,15)
C <- rep(5,19)
D <- c(1:19)
data1 <- tibble(A, B, C, D)
data1 <- gather(data1, Type, Value, -D)

plot <- ggplot(data = data1, aes(x = D, y = Value))+
  theme_light()+
  geom_line(aes(colour = Type), size=0.75)+
  theme(legend.title = element_blank())

Example

The original graphs look like this but they are made in pretty much the same way as in the example:

Original

The issue is that I want to crop A (red in example; solid blue line in the original graphs) when it hits C (blue in example; solid red line in original graph) without affecting B (green in example; everything else in original graph).

The complication is that I don't really want to change the structure of my original dataset so I'm hoping that there's a way of doing this while I'm creating the plot?

Many thanks,

Carolina

Upvotes: 1

Views: 627

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

Yes, you can do it within the ggplot call by passing a filtered version of the data frame to the data argument of geom_line:

ggplot(data = data1, aes(x = D, y = Value))+
  theme_light() +
  geom_line(aes(colour = Type), 
            data = data1 %>% 
              filter(!(Type == "A" & Value > mean(Value[Type == "C"]))), 
            size = 0.75)+
  theme(legend.title = element_blank())

enter image description here

However, from looking at your original plot, I think the tidiest way to do this would be to narrow the x axis limits to "chop off" either end of the lower blue line where it meets the horizontal red line, since this will not affect the dashed upper blue line at all. You can cut off the data with lims(x = c(0.25, 12.5) but retain the lower limit of 0 on your axis by setting coord_cartesian(xlim = c(0, 12.5))

Upvotes: 2

Related Questions