How to smooth a line in R ggplot

I am trying to display the observed values ​​as points against the expected values ​​as a string as follows:

d <- data.frame(
    ranks = 1:9,
    observed = c(0.736, 0.121, 0.067, 0.034, 0.026, 0.015, 0.001, 0.001, 0.000),
    expected = c(0.735, 0.136, 0.051, 0.025, 0.015, 0.009, 0.006, 0.005, 0.003)
)

ggplot(d, aes(x=ranks, y=observed)) +
  geom_point(size=2.2) +
  geom_line(aes(x=ranks, y=expected), size=0.8, colour='red')

enter image description here

This is correct, but I would prefer the line to be well-smoothed (without elbows). Using geom_smooth()with loessor gamdoesn't really help how to re-affirm anti-aliasing (in different ways). Any suggestion?

Update: If this is useful, here is how I created the expected values:

# BACIS POWER FUNCTION:
fPow <- function(x, a, b) {a * x^b}

# INITIALIZE PARAMETERS:
est1 <- coef(nls(observed ~ fPow(ranks, a, b),
    start=c(a=1, b=1), data=d))

# FITTING:
nlfit1 <- nls(observed ~ fPow(ranks, a, b),
    start=est1, data=d)

# EXPECTED VALUES:
expected <- predict(nlfit1)
+4
source share
1 answer

One solution you can try is a spline that has to go through the expected points:

library(ggplot2)
library(ggalt)

d <- data.frame(
  ranks = 1:9,
  observed = c(0.736, 0.121, 0.067, 0.034, 0.026, 0.015, 0.001, 0.001, 0.000),
  expected = c(0.735, 0.136, 0.051, 0.025, 0.015, 0.009, 0.006, 0.005, 0.003)
)

ggplot(d, aes(x = ranks, y = observed)) +
  geom_point(size = 2.2) +
  geom_xspline(aes(y = expected), size = 0.8,
               spline_shape = -.15, colour = 'red')

enter image description here

This approach always works, but I'm not a big fan of splines for data visualization, since they make up data that we don’t have.

The best approach, I think, is to interpolate the prediction formula for fractional ranks:

fPow <- function(x, a, b) {a * x^b}
est1 <- coef(nls(observed ~ fPow(ranks, a, b),
                 start=c(a=1, b=1), data=d))
nlfit1 <- nls(observed ~ fPow(ranks, a, b),
              start=est1, data=d)

d2 <- data.frame(ranks = seq(1, 9, by = 0.1))
expected <- predict(nlfit1, d2)
d2 <- data.frame(d2, expected)

ggplot(d, aes(x = ranks, y = observed)) +
  geom_point(size = 2.2) +
  geom_line(data = d2, aes(x = ranks, y = expected), size = 0.8, colour = 'red')

enter image description here

+3
source

Source: https://habr.com/ru/post/1692166/


All Articles