kolas0202
kolas0202

Reputation: 173

Exclude a particular area from geom_smooth fit automatically

I am plotting different plots in my shiny app.

By using geom_smooth(), I am fitting a smoothing curve on a scatterplot.

I am plotting these plots with ggplot() and rendering with ggplotly().

Is there any way, I can exclude a particular data profile from geom_smooth().

For e.g.: enter image description here

It can be seen in the fit, the fit is getting disturbed and which is not desirable. I have tried plotly_click(), plotly_brush(), plotly_select(). But, I don't want user's interference when plotting this fit, this makes the process much slower and inaccurate.

Here is my code to plot this:

#plot
    g <- ggplot(data =  d_f4, aes_string(x = d_f4$x, y = d_f4$y)) + theme_bw() +
          geom_point(colour = "blue", size = 0.1)+
          geom_smooth(formula = y ~ splines::bs(x, df = 10), method = "lm", color = "green3", level = 1, size = 1)

Unfortunately, I can not include my dataset in my question, because the dataset is quite big.

Upvotes: 0

Views: 159

Answers (1)

starja
starja

Reputation: 10365

You can make an extra data.frame without the "outliers" and use this as the input for geom_smooth:

set.seed(8)
test_data <- data.frame(x = 1:100)
test_data$y <- sin(test_data$x / 10) + rnorm(100, sd = 0.1)
test_data[60:65, "y"] <- test_data[60:65, "y"] + 1

data_plot <- test_data[-c(60:65), ]

library(ggplot2)

ggplot(data =  test_data, aes(x = x, y = y)) + theme_bw() +
  geom_point(colour = "blue", size = 0.1) +
  geom_smooth(formula = y ~ splines::bs(x, df = 10), method = "lm", color = "green3", level = 1, size = 1)

ggplot(data =  test_data, aes(x = x, y = y)) + theme_bw() +
  geom_point(colour = "blue", size = 0.1) +
  geom_smooth(data = data_plot, formula = y ~ splines::bs(x, df = 10), method = "lm", color = "green3", level = 1, size = 1)

Created on 2020-11-27 by the reprex package (v0.3.0)

BTW: you don't need aes_string (which is deprecated) and d_f4$x, you can just use aes(x = x)

Upvotes: 0

Related Questions