Same data set, two lines, two equations, on the same graph?

Asked

Viewed 66 times

-2

My data fits easily by a straight line, but even better by 2, dividing the data. I need to divide the data into 2 parts, thus: concentrations (x) up to 700 ppm and concentrations > or = 700 ppm. And I may have to change this 700, like the border between straight lines.

What is the simplest way to get a graph showing two linear lines and their equations and R 2 ?

EDIT: I am trying to develop the solution with R (I accept other forms).

I created a subset of my <700 data and am adjusting a linear model here.

  • 3

    Welcome to Stackoverflow! Unfortunately, this question cannot be reproduced by anyone trying to answer it. Please, take a look at this link and see how to ask a reproducible question in R. So, people who wish to help you will be able to do this in the best possible way.

  • 2

    It’s Python, R or Excel?

  • Actually, it’s the one that can solve the problem. I’m more comfortable with R, but I understand myself in Python. Thank you.

1 answer

2


To trace two regression lines, you first have to create an extra variable, which tells what part each data group belongs to, if x < 700, if x >= 700.

library(ggplot2)


df$group <- factor(as.integer(df$x < 700))

ggplot(df, aes(x = z, y = x, colour = group)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE)

inserir a descrição da imagem aqui

Dice.

This code is used to create a fictitious data set.

set.seed(1234)    # Torna os resultados reprodutíveis

n <- 100
x1 <- runif(n, 0, 700)
x2 <- runif(n, 700, 1400)
x <- 0.75*x1 + 2 + rnorm(n, sd = 16)
x <- c(x, 2*x2 + 1 + rnorm(n, sd = 25))
df <- data.frame(x, z = c(x1, x2))
  • And how to get the corresponding equations and R 2 to appear?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.