14

我编写了一个函数来使用函数获取比例堆积条形图ggplot。现在我在这个中使用列名ID

PropBarPlot<-function(df, mytitle=""){
    melteddf<-melt(df, id="ID", na.rm=T)
    ggplot(melteddf, aes(ID, value, fill=variable)) + 
      geom_bar(position="fill") + 
      theme(axis.text.x = element_text(angle=90, vjust=1)) + 
      labs(title=mytitle)
}

我想让它通用。所以我想使用列索引而不是列名。我试着做这样的事情。

PropBarPlot<-function(df, mytitle=""){
    melteddf<-melt(df, id=names(df)[1], na.rm=T)
    ggplot(melteddf, aes(names(df)[1], value, fill=variable)) + 
      geom_bar(position="fill") + 
      theme(axis.text.x = element_text(angle=90, vjust=1)) + 
      labs(title=mytitle)
}

但是没有用。有人可以建议我怎么做吗?

谢谢。

4

2 回答 2

13

正如@baptiste 所指出的,您应该在定义 x 和 y 值时使用aes_string()而不是使用字符串。aes()你也应该在引号value内加上variable引号。

PropBarPlot<-function(df, mytitle=""){
  melteddf<-melt(df, id=names(df)[1], na.rm=T)
  ggplot(melteddf, aes_string(x=names(df)[1],y= "value", fill="variable")) + 
    geom_bar(position="fill") + 
    theme(axis.text.x = element_text(angle=90, vjust=1)) + 
    labs(title=mytitle)
}
于 2013-04-24T08:48:11.353 回答
1

正如@Bryan Shalloway 所指出的,该aes_string()方法现在已被软性弃用,取而代之的是整洁的评估。使用整洁的评估方法,我的解决方案是:

library(reshape)
library(ggplot2)

# let's start by creating an example dataframe
id <- c(1, 2, 3, 4)
var1 <- c(10, 20, 10, 20)
var2 <- c(6, 3, 2, 5)
df <- data.frame(id, var1, var2)

# Now let's build the function
PropBarPlot<-function(df, mytitle=""){
  # here I create a variable that contains the first element of the vector 
  # of df column names (it's a string)
  my_name <- colnames(df)[1]
  # here we melt, using the new variable as the id parameter
  melteddf<-melt(df, id=my_name, na.rm=T)
  # and here we plot, using the .data pronoun and the new variable
  ggplot(melteddf, aes(x = .data[[my_name]],y = value, fill = variable)) + 
    geom_bar(position="fill", stat="identity") + 
    theme(axis.text.x = element_text(angle=90, vjust=1)) + 
    labs(title=mytitle)
}

如果您想了解更多关于 tidy 评估的信息(带有分步说明和实际示例),我衷心推荐 Ian Lyttle 的学习者教程,可在https://ijlyttle.shinyapps.io/tidyeval/

于 2021-10-14T06:42:37.197 回答