使用aes_string时,格式化geom_text标签不起作用 [英] Format geom_text label doesn't work when using aes_string
本文介绍了使用aes_string时,格式化geom_text标签不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用点函数来格式化用ggplot2
创建的绘图中的文本标签.使用aes
时,此方法工作正常,但使用aes_string
时,效果不佳.是否有一种变通办法可以使其与aes_string
一起使用?
I am using the dot function to format text labels in a plot created with ggplot2
. This works fine when using aes
, but doesn't work like expected when using aes_string
. Is there a workaround to make it work with 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")))
推荐答案
您不仅要引用"X2",还必须引用整个表达式
Rather than just quote "X2", you must quote the whole expression
ggplot(iris) +
geom_bar(aes(Species, Sepal.Width), stat = "identity") +
geom_text(data=df, aes_string(x="X1", y =180, label = "dot(X2)"))
如果要通过字符向量指定变量名,则可以使用paste()
来构建该表达式.
If you wanted to specify variable names via a character vector, you would use paste()
to build that expression.
这篇关于使用aes_string时,格式化geom_text标签不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文