简体   繁体   中英

Cannot adjust logarithmic curve using ggplot2 in R

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.

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:

在此处输入图像描述

在此处输入图像描述

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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM