r - nls and log scale in ggplot2 -
I'm trying to plot 3 non-linear models in ggplot2 It is working on automatic scale but the log is not in scale 10 where I get "singular gradient error". What can be the problem (s)?
The data that I am trying to fit (df1):
xy 4.17 0.55 10.08 0.48 40.25 0.38 101.17 0.32 400.33 0.24
I have tried the code:
plot & lt; - ggplot (df1, aes (x = x, y = y)) + stat_smooth (method = "Nls", formula = y ~ i (a * x ^ (- n)), data = df1, start = list (a = 1, n = 1), se = FALSE, color = "red") + stat_smooth (method = "Nls", formula = y ~ m * (x + m ^ (1 / n)) ^ (-n) Data = df1, start = list (m = 0.7, n = 0.17), se = false, color = "blue") + stat_smooth (method = "nls", formula = y ~ m * (x + m ^ (1 / N)) ^ (- n) + b, data = df1, start = list (m = 0.7, n = 0.17, b = 1), se = FALSE, color = "green") + geom_point () + scale_x_log10 () + Scale_y_log10 () + theme_bw () plot
The problem is that when you type the Scale_x_log10
or scale_y_log10
, the values of your statistics are different stats or geographies Prior to the passage of link conditions are changed. This means that when your NLS can work on enormous data, it does not work on log-transformed data.
# OK NLS (y ~ m * (x + m ^ (1 / n))) ^ (- n), df1, start = list (m = 0.7, n = 0.17) ) # Not OK NLS (y ~ m * (x + m ^ (1 / n)) ^ (-n), log 10 (Df1), start = list (m = 0.7, n = 0.17))
It does not seem that you can do this in ggplot2
to fix this. Instead, you can fit NLS models on time without transformed scale and just plot results with ggplot2. For example
mods & lt; -list (list (y ~ i (a * x ^ (- n)), list (a = 1, n = 1)), list (y ~ m * (x + m ^ (1 / n)) ^ - N), list (M = 0.7, n = 0.17), list (y ~ m * (x + m ^ (1 / n)) ^ (-n) + b, list (m = 0.7, n = 0.17 , B = 1)) fits & lt; -apply (mods, function (x, xr) {mod & lt; -nls (x [[1]], data = df1, start = x [2]] ) Xx & lt; -seq (xr [1], xr [2], length out = 100) yy & lt; -predict (mod, newdata = data.frame (x = xx)) data .frame (x = xx , Y = yy)}, xr = class (df1 $ x) library (ggplot2) ggplot (df1, aes (x = x, y = y)) + geom_line (data = fits [[Geom_line (data = 1 = Fits [[2]], color = "blue") + geom_line (data = fits [[3]], color = "green") + geom_point () + Scale_x_log10 () + scale_y_log10 () + theme_bw ()
will generate
Comments
Post a Comment