Philippe Ear
Philippe Ear

Reputation: 25

Hiding/Removing part of a curve in R

I'd like when plotting a curve from a set of data, hiding parts that meet some conditions, for example, hiding everything with a value > 10 on the y axis.

I can't just set the value to 0 or to a really high number and just use xlim or ylim since the moment I plot with a line type, I will have a vertical line and I don't want that.

x <- seq(from=-50,to=50,by=0.1)
#I'd like every part of the curve above 1000 to disappear for example
y<--x^2+2500
plot(x,y,type="l")
y[y>1000]<-0
#this will create two vertical lines
plot(x,y,type="l")

Wanted :

Imgur

Actual result:

img

Upvotes: 0

Views: 1007

Answers (1)

Max Teflon
Max Teflon

Reputation: 1800

x <- seq(from=-50,to=50,by=0.1)
y<--x^2+2500
ylims <- range(y)
plot(x,y,type="l",ylim = ylims)

y[y>1000]<-NA
plot(x,y,type="l", ylim = ylims)


## tidyverse ====
x <- seq(from=-50,to=50,by=0.1)
y<--x^2+2500
library(tidyverse)

p <- tibble(x,y) %>%
  mutate(yCutoff = ifelse(y>1000, NA, y)) %>%
  ggplot(aes(x,y)) +
  geom_line(aes(y = yCutoff)) +
  ylim(range(y)) +
  theme_minimal()
p

# your x-Values:
p$data  %>% filter(is.na(yCutoff))%>% select(x)
#> # A tibble: 775 x 1
#>        x
#>    <dbl>
#>  1 -38.7
#>  2 -38.6
#>  3 -38.5
#>  4 -38.4
#>  5 -38.3
#>  6 -38.2
#>  7 -38.1
#>  8 -38  
#>  9 -37.9
#> 10 -37.8
#> # … with 765 more rows

Upvotes: 3

Related Questions