0

Is there a way to plot a line (with different X variable) on top of a scatterplot in R.?

Despite trying different ways the desired plot doesn't come.

Example of a try is shown below..

library(ggplot2)
ggplot(mtcars)+
  geom_point(mapping= aes(wt,mpg))+
   geom_line(mapping= aes(x=hp,y=mpg))

But this gives a weird result.

Output

Thanks in advance for the help !

Salih
  • 391
  • 1
  • 13
  • 2
    Of course it works, exactly they way you did it. But the points and lines you have chosen have completely different ranges of values. `wt` has a range of 1.5-5.4 whereas `hp` has a range of 52-335. Perhaps you can be a little more clear and specific about what your desired outcome should look like? – cymon Dec 02 '19 at 16:31
  • A good way to fix this is by coloring points based on a grouping variable. This way you can look at three different variables at the same time without having to worry about values. Just create a grouping variable and use that in the color element of the geom_whatever() function – Hansel Palencia Dec 02 '19 at 20:11

1 Answers1

1

You could try to solve this by secundary axes, but I feel obligated to communicate warnings given here and elsewhere. That said, here is how you could do it.

First, we'll make a function that can rescale data from one range to another range

# x is variable to be rescaled
# y is a range to be rescaled towards
scaling <- function(x, y) {
  y <- range(y)
  x <- (x - min(x)) / (max(x) - min(x))
  x * diff(y) + min(y)
}

Then we'll use this function in the aes() of hp and in the secondary axis. Colours are added for clarity.

ggplot(mtcars)+
  geom_point(mapping = aes(wt, mpg, colour = "wt"))+
  geom_line(mapping = aes(x = scaling(hp, wt), y = mpg, colour = "hp")) +
  scale_x_continuous(sec.axis = sec_axis(~ scaling(., mtcars$hp), name = "hp"))

enter image description here

teunbrand
  • 33,645
  • 4
  • 37
  • 63