Reputation: 177
I have 50 data points of temperature and humidity that I would like to plot on geom_point and add a linear model to my ggplot
. however, I am unable to do so. I have tried abline
, geom_line
, geom_smooth
and lm
.
temp_humidity_data <- dplyr::select(data, temperature:humidity)
lm(formula = humidity ~ temperature, data = temp_humidity_data)
ggplot(temp_humidity_data) +
geom_point(aes (x = temperature , y = humidity))
geom_smooth()
How can I go about adding an lm
to my `ggplot? any help is appreciated. thank you. And how could i differentiate the temperature and humidity points by colour as well on the plot?
this is what I have currently ^
Upvotes: 0
Views: 120
Reputation: 18681
As mentioned in the comment section, you missed a +
sign after geom_point
. Besides that, you are also missing a few arguments in geom_smooth
:
library(ggplot2)
ggplot(iris) +
geom_point(aes(x = Petal.Length , y = Petal.Width)) +
geom_smooth(aes(x = Petal.Length, y = Petal.Width),
method = "lm", formula = y ~ x)
You need to supply "aesthetics" for x
and y
, otherwise you would get the following error:
Error: stat_smooth requires the following missing aesthetics: x, y
method = "lm"
tells geom_smooth
that you want to use the linear model method while formula
specifies the model formula to plot. If we don't specify the method
, geom_smooth
defaults to "loess" (as stated by @Lyngbakr) and gives the warning message:
geom_smooth()
using method = 'loess' and formula 'y ~ x'
Since we have to supply the same aesthetics in both geom_point
and geom_smooth
, a more convenient way would be to write:
ggplot(iris, aes(x = Petal.Length , y = Petal.Width)) +
geom_point() +
geom_smooth(method = "lm", formula = y ~ x)
Output:
To answer OP's second question of "how could i differentiate the temperature and humidity points by colour as well on the plot?", we can add the color
and size
aesthetics to geom_point
like the following:
ggplot(iris, aes(x = Petal.Length , y = Petal.Width)) +
geom_point(aes(color = Petal.Length, size = Petal.Width)) +
geom_smooth(method = "lm", formula = y ~ x)
Output:
To change the range of sizes and colors, we use scale_fill_continuous
(or scale_color_continuous
for color
) and scale_size_continuous
:
ggplot(iris, aes(x = Petal.Length , y = Petal.Width)) +
geom_point(aes(fill = Petal.Length, size = Petal.Width), pch = 21) +
geom_smooth(method = "lm", formula = y ~ x) +
scale_fill_continuous(low = "red", high = "blue") +
scale_size_continuous(range = c(1, 10))
Notice that as you increase the size
range, some points start to overlap with each other. To make it less confusing, I've used fill
instead of color
and added pch = 21
("plot character" of a circle) to wrap around each point. This gives a nice border that separates each point.
Output:
Upvotes: 1