在 R 中使用 stat_function 用图例绘制多个函数

问题描述 投票:0回答:1

我正在尝试创建一个具有多个函数的绘图。每个函数都由数据帧中的系数定义,数据帧的每一行包含一个函数的系数和该组的标识符。

目标是让 stat_function 使用数据框中的系数绘制线条,但没有 x 的实际数据。每条线都应该有唯一的颜色并列在图例中

我见过添加几个 stat_functions 并单独定义颜色的示例here。我想避免这种情况,使函数动态化,并能够以最小的变化绘制可变数量的函数。

here找到的答案与我正在寻找的非常接近,但是每个函数都有相同的颜色并且没有图例。

我成功地输出了一个具有独特颜色但没有图例的图,以及具有图例但只有一种颜色的图。

这是我在 ggplot 中绘制的示例:

library(plyr)

#create data frame

qr <- c(0.11,0.11,0.11,0.05)
qs <- c(0.98,0.98,0.97,0.93)
alpha <- c(78.0564,141.017,58.0405,12.6902)
n <- c(1.53364,1.37685,1.42174,1.15284)
ks <- c(9.936,3.915563,04575,0.312171)
l <- c(-0.09953,-1.5645,-0.12945,2.16382)
m <- 1-1/n
depth <- c(1,2,3,4)

coefs <- data.frame(qr,qs,alpha,n,ks,l,m,depth)

#legend one colour
coeflines1 <-
  alply(as.matrix(coefs), 1, function(coef) {
    stat_function(fun=function(x)
      {coef[1]+(coef[2]-coef[1])/((1+(coef[3]*x)^coef[4])^coef[7])},
      aes(colour = as.factor(depth[1])))
  })

ggplot(data.frame(x=c(0.001, 10)), aes(x=x)) + 
  coeflines1 +
  scale_x_log10()

#no legend multile colour
coeflines2 <-
  alply(as.matrix(coefs), 1, function(coef) {
    stat_function(fun=function(x)
    {coef[1]+(coef[2]-coef[1])/((1+(coef[3]*x)^coef[4])^coef[7])},
    colour = coef[8])
  })

ggplot(data.frame(x=c(0.001, 10)), aes(x=x)) + 
  coeflines2 +
  scale_x_log10()

第一个示例的问题是它没有引用函数内的任何内容。如果

depth[1]
更改为
coef[8]
我得到
Error in coef[8] : object of type 'closure' is not subsettable

在第二个示例中,没有出现图例,因为我没有绘制美学图。如何映射与数据框系数的最后(第 8)列相对应的美学?

r ggplot2 legend
1个回答
0
投票

您遇到的一个问题是有一个函数

coef
。当你看到有关“关闭”的抱怨时,这就是原因。它正在查看函数,而不是匿名函数中的参数。

其次,当仅绘制没有数据的函数时,

stat_function
的帮助说明“指定x轴的范围”并给出了使用
xlim
的示例。由于您已经有了
x
轴规范,因此您需要在其中包含限制。

plyr
包相当旧(现在,认识到这个问题是6年前的事了),所以我改用了
purrr
中的函数。另外,我清理了数据创建代码,以免留下对象,这可能会使“找到”正确的对象变得更加困难。

library(tidyverse)

coefs <- 
  data.frame(
    qr = c(0.11,0.11,0.11,0.05),
    qs = c(0.98,0.98,0.97,0.93),
    alpha = c(78.0564,141.017,58.0405,12.6902),
    n = c(1.53364,1.37685,1.42174,1.15284),
    ks = c(9.936,3.915563,04575,0.312171),
    l = c(-0.09953,-1.5645,-0.12945,2.16382),
    m = 1 - 1/c(1.53364,1.37685,1.42174,1.15284),
    depth = c(1,2,3,4))

coeflines1 <-
  pmap(
    .l = coefs, 
    .f = \(qr, qs, alpha, n, ks, l, m, depth) 
      stat_function(
      fun=function(x) {
        qr+(qs-qr)/((1+(alpha*x)^n)^m)
      },
      aes(colour = factor(depth))
      )
  )

ggplot() +
  coeflines1 +
  scale_x_log10(limits = c(0.001, 10))

Plot of multiple functions dependent on a matrix of coefficients using ggplot2

© www.soinside.com 2019 - 2024. All rights reserved.