将列标题粘贴为轴标签

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

我有一个大数据框。我想使用函数快速绘制每个列。我在获取Y轴标签以匹配列标题方面遇到麻烦。

这里是一个示例数据帧。假设我要创建两个图,名称为1和名称2为每个图的y轴。

 dat <- data.frame(X = c(1, 2, 3, 4),
              name1 = c(50, 100, 200, 250),
              name2 = c(10, 20, 30, 40))

我写了一个函数来创建图形

 plot <- function (dat, col) {
   ggplot(dat, aes(x = X, y= {{col}}, group=1))+
     geom_point(size = 1)+
     geom_line(size = 0.5)+
     theme(axis.text.y = paste0({{col}}, "plus units and other text"))
 }

然后我要为“ name1”列创建图形

 plot(dat, name1)

如果我从功能代码中删除主题行,这将起作用。我想在Y轴上说“ name1加上单位和其他文字”。

r function ggplot2 label paste
2个回答
0
投票

您可以使用aes_string并将name1-参数作为字符串起作用。您也可以使用labs命名轴标题。

plot <- function(dat, col) {
  ggplot(dat, aes(x = X)) +
    geom_point(aes_string(y=col)) +
    geom_line(aes_string(y=col)) +
    labs(y = paste0(col, "plus units and other text"))
}
plot(dat, 'name2')


@camilles评论后编辑。第二种选择:
plotB <- function (dat, col) {
  colA <- enquo(col)
    ggplot(dat, aes(x = X, y= !!colA))+
      geom_point(size = 1)+
      geom_line(size = 0.5) +
      ylab(paste(quo_name(colA), ' Units'))
}

plotB(dat, name2)

0
投票

[如果要为col使用变量,则在函数内部,可以执行replace()来捕获col的表达式,并注意应使用ylab而不是theme(..)来更改y标签:

    plot <- function (dat, col) {
   ggplot(dat, aes(x = X, y= {{col}}, group=1))+
     geom_point(size = 1)+
     geom_line(size = 0.5)+
     ylab(substitute(col))
     #ylab()
 }

如果需要在ylab上附加一个更复杂的表达式,请执行以下操作:

plot <- function (dat, col) {
   LAB=substitute(V:Ca ~ (µmol ~ mol^{-1}) , list(V = substitute(col)))
   ggplot(dat, aes(x = X, y= {{col}}, group=1))+
     geom_point(size = 1)+
     geom_line(size = 0.5)+
     ylab(LAB)
 }

请检查this chapter on quasiquotations以更好地使用它们。

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