r - How to draw a power curve using ggplot2 -


i want use ggplot2 visualize data follows power curve. has been asked before (add exp/power trend line ggplot) answer didn't help.

one trick use stat_function() create curve. however, unable stat_function() , power curve work logarithmic scales.

i illustrate problems.

create sample data , base plot:

library(ggplot2)  x <- 1:100 pwr <- function(x)x^-2.5 dat <- data.frame(x, y = pwr(x))  p <- ggplot(dat, aes(x = x, y = y)) +    geom_point()  p + stat_function(fun = pwr) 

enter image description here

great, let's add logaritmic scales using coord_trans(). works perfectly, except straight lines no longer straight (exactly documentation tells me expect).

p + stat_function(fun = pwr) + coord_trans(x = "log10", y = "log10") 

enter image description here

so, try again coord_x_log10() , coord_y_log10(), throws error:

p + stat_function(fun = pwr) + scale_x_log10() + scale_y_log10()  error in seq.default(min, max, = by) :    'from' cannot na, nan or infinite 

this has fact have adjust function invert effect of scales, can't quite figure out.

i can logarithmix x-scale:

p + scale_x_log10() + stat_function(fun = function(x)pwr(10^x)) 

enter image description here

i have no idea how convert y-values if add scale_y_log10().

i'm missing fundamental. there easy way plot curve?

putting comments answer:

the main problem bug in stat_function. when used in conjunction axis transformations calculates y-values transformed , not original values. has been fixed on github recently.

however, not easy see since first error occurs when calculating axis breaks since bug produces inf, 0 and/or negative y-values. need set explicit axis limits see actual problem stat_function:

p + stat_function(fun = pwr) +    scale_x_log10() + scale_y_log10(limits = c(1e-5, 1)) #warning message: #removed 100 rows containing missing values (geom_path). 

resulting plot

it's more obvious if transform x-axis:

p + stat_function(fun = pwr) +    scale_x_log10()  

resulting plot

if can't use ggplot2 version github use this:

p + geom_line(data = data.frame(x = seq(min(dat$x), max(dat$x), length.out = 100)),               aes(y = pwr(x))) +    scale_x_log10() + scale_y_log10() 

resulting plot


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -