使用aes_string时,格式geom_text标签不起作用

JT8*_*T85 5 r ggplot2

我使用点函数来格式化创建的图中的文本标签ggplot2.这在使用时工作正常aes,但在使用时不能像预期的那样工作aes_string.是否有解决方法使其适用aes_string

require(ggplot2)

# Define the format function
dot <- function(x, ...) { 
  format(x, ..., big.mark = ".", scientific = FALSE, trim = TRUE)
}

# Create dummy data
df <- data.frame(cbind(levels(iris$Species),c(10000000000,200000,30000)))
df$X2 <- as.numeric(as.character(df$X2))

# Works with aes   
ggplot(iris) + 
  geom_bar(aes(Species,Sepal.Width),stat="identity") +     
  geom_text(data=df,aes(x=factor(X1),y=180,label=dot(X2)))


# Doesn't work with aes_string
ggplot(iris) + 
  geom_bar(aes(Species,Sepal.Width),stat="identity") +
  geom_text(data=df,aes_string(x="X1",y=180,label=dot("X2")))
Run Code Online (Sandbox Code Playgroud)

MrF*_*ick 3

您必须引用整个表达式,而不是仅仅引用“X2”

ggplot(iris) + 
  geom_bar(aes(Species, Sepal.Width), stat = "identity") + 
  geom_text(data=df, aes_string(x="X1", y =180, label = "dot(X2)"))
Run Code Online (Sandbox Code Playgroud)

如果您想通过字符向量指定变量名称,您可以使用paste()构建该表达式。