有没有办法在ggplot2中使用函数参数作为标签?

时间:2016-07-21 18:33:52

标签: r ggplot2

快速提问:如果我想运行一个函数,例如plt.diff(dataset1),并且在输出图中,我希望函数使用名称“dataset1”作为y轴标签,这怎么可能是做什么?

plt.diff <- function(x){ 
  x$kind <- as.factor(x$kind)
    ggplot(x,aes(x=as.factor(nodes), fill= age)) + labs(title = 'Difference plot',
                x = 'points', y = deparse(substitute(x)) ) + geom_text(
                aes(label = nodes, y = diff)) +
                geom_bar(stat="identity", aes(y = diff)) + 
                geom_bar(stat="identity", aes( y = (diff*(-1)))) + 
                coord_flip()}

正如您所看到的,我已经尝试了deparse(substitute(x)),但它不起作用。这是当前y轴的输出: structure(list(nodes= structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L))))

1 个答案:

答案 0 :(得分:0)

我会在早期通过deparse(substitute(x))提取传递给函数的对象的名称,然后将其传递给 ggplot。这可以确保对象的名称基于传递给plt.diff的函数参数而不是 到plt.diff中的ggplot。

使用玩具数据集:

dataset1 <- data.frame(nodes = 1:10, kind = 1:10, age = rpois(10, 20), diff = rpois(10,5))

library(ggplot2)

plt.diff <- function(x){
  x_name <- deparse(substitute(x))  
  x$kind <- as.factor(x$kind)
  ggplot(x, aes(x = as.factor(nodes), fill = age)) + 
    labs(title = 'Difference plot', x = 'points', y = x_name) + 
    geom_text(aes(label = nodes, y = diff)) +
    geom_bar(stat="identity", aes(y = diff)) + 
    geom_bar(stat="identity", aes( y = (diff*(-1)))) + 
    coord_flip()}

plt.diff(dataset1)

ggplot2 bar chart