【问题标题】:Non Standard Evaluation with ggplot2 in R在 R 中使用 ggplot2 进行非标准评估
【发布时间】:2018-04-27 17:48:37
【问题描述】:

我在下面有一个相当简单的函数,它将一个数据框和该数据框中的一列作为参数。该函数在 y 轴上绘制数据框中的列,在 x 轴上绘制“年份”列。然后它将在图上的点旁边显示相关列的值。

df_to_plot = data.frame(year = c(2011, 2012, 2013), data=c(0.22334, 0.345345, 0.456234))

makePlotFunc = function(df, y_var)
{
    ggplot(df, aes_(x=as.name("year"), y = as.name(y_var), group=1, label=as.name(y_var))) + geom_point() + geom_line() + geom_text()
}

makePlotFunc(df_to_plot, data)

不过,您会注意到“数据”列有很多小数点。我希望能够对这些小数点进行四舍五入,以便在绘图上显示这些数据点时看起来不错。通常,当不使用“非标准评估”时,可以很容易地在 geom_text() 中完成,如下所示:

geom_text(aes(round(data, 2))

因为我用非标准评估把它变成了一个函数,所以不能这样。

geom_text(aes_(round(as.name(y_var), 2)))

这会引发错误。

non-numeric argument to mathematical function

我通过在数据框中创建一个新列作为标签解决了我的问题。

df_to_plot = mutate(df_to_plot, label = as.character(round(data, 2)))

尽管如此,如果有人知道我如何使用非标准评估来做到这一点,我仍然很感兴趣。

【问题讨论】:

  • 现在尝试使用bquotegeom_text(aes_(label=bquote(round(.(as.name(y_var)), 3))))。支持 rlang 样式引用的 ggplot 的下一个版本。

标签: r ggplot2 dplyr rlang


【解决方案1】:

感谢 MrFlick 的回答。成功了!

geom_text(aes_(label=bquote(round(.(as.name(y_var)), 3))))

【讨论】:

    猜你喜欢
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 1970-01-01
    相关资源
    最近更新 更多