gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:00:45 27 4
gpt4 key购买 nike

我正在使用 dot 函数来格式化使用 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")))

最佳答案

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

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

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

关于r - 使用 aes_string 时,格式 geom_text 标签不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24292886/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com