How to smooth this graph in R/Rstudio?

Asked

Viewed 560 times

3

If I plot the chart normally

pontos.x = c(7.522936, 12.228712, 17.316037, 22.148996, 27.236321, 32.196464, 37.283789, 
42.116748, 47.076890, 52.164215, 57.378723, 62.211682, 67.426190)

pontos.y = c(0.001583012, 0.001583012, 0.013938224, 0.017799228, 0.034015444, 
0.032374517, 0.037876448, 0.023880309, 0.017799228, 0.010849421, 0.003030888, 
0.003899614, 0.001583012)

plot(pontos.x, pontos.y, type = "l")

it plots normally, but the curve gets straight (?). If anyone can help, I wanted the dots to be connected but by curves and not by straights, as if it were a Smooth, I already researched but no solution, because I need to make a histogram and pass a curve with those dots on top of it (add = T).

1 answer

3

One way to make this smoothing is to first choose a tool capable of generating the curve that will interpolate your data. My suggestion is to do a loess regression of pontos.y in pontos.x and plot these data on top of the histogram through the function lines:

x <- rnorm(1000, mean=37.5, sd=10)
hist(x, prob=TRUE)
ajuste <- loess(pontos.y ~ pontos.x)
lines(pontos.x, predict(ajuste))

inserir a descrição da imagem aqui

If the overlapping curve was not ideal, I suggest finding the best values for the arguments span and degree of function loess.

Another way to do this is to use the function density, where she herself is an estimator of the density function of your data. Particularly, it is my preferred solution:

hist(x, prob=TRUE)
lines(density(x))

inserir a descrição da imagem aqui

A third way is to use the package ggplot2 to make the histogram and simultaneously estimate the density function of the sample data:

dados <- data.frame(x=x)

library(ggplot2)
ggplot(dados, aes(x)) +
  geom_histogram(aes(y=..density..)) +
  geom_density(alpha=.2, fill="white")

inserir a descrição da imagem aqui

  • Thank you, Marcus.

Browser other questions tagged

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