Cannot adjust logarithmic curve using ggplot2 in R

Viewed 40

I am trying to plot an adjustable logarithmic curve with ggplot2. From various Stack Overflow posts I was able to create this:

key <- c(1,2,300)
value <- c(10, 20, 300)
dummyData <- data.frame(key, value)

# ggplot graph plotting
graph <- ggplot(dummyData, mapping = aes(x=key, y=value))+
  stat_smooth(
    method = 'nls',
    formula = 'y ~ a * log(x) + b',
    method.args = list(
      start = list(a = 1, b = 1)
    ),
    se = FALSE
    )
print(graph)

However, no matter what extreme value I put the start = list(a = 1, b = 1) line, I couldn't adjust the logarithmic curve at all.

1 Answers

Try this enabling the lower/upper options from nls(). As you can see the curves have changed:

library(ggplot2)
# ggplot graph plotting 1
graph <- ggplot(dummyData, mapping = aes(x=key, y=value))+
  stat_smooth(
    method = 'nls',
    formula = 'y ~ a * log(x) + b',
    method.args = list(
      start = list(a = 1, b = 1),
      lower = c(1, 1),
      upper = c(1, 1),algorithm = "port"
    ),
    se = FALSE
  )
print(graph)


# ggplot graph plotting 2
graph <- ggplot(dummyData, mapping = aes(x=key, y=value))+
  stat_smooth(
    method = 'nls',
    formula = 'y ~ a * log(x) + b',
    method.args = list(
      start = list(a = 999, b = 999),
      lower = c(999, 999),
      upper = c(999, 999),algorithm = "port"
    ),
    se = FALSE
  )
print(graph)

Outputs:

enter image description here

enter image description here

Or this:

# ggplot graph plotting 3
graph <- ggplot(dummyData, mapping = aes(x=key, y=value))+
  stat_smooth(
    method = 'nls',
    formula = 'y ~ a * log(x) + b',
    method.args = list(
      start = list(a = 1, b = 1),
      lower = c(1, 1),
      upper = c(10, 20),algorithm = "port"
    ),
    se = FALSE
  )
print(graph)

Output:

enter image description here

Related