将来自不同环境的值传递给 ggplot aes()?
passing values from different environments to ggplot aes()?
我将其作为 RShiny 应用程序的一部分:
sizeToUse = eval(length(levels(factor(df2$Cluster))))
ggplot(df2, aes(x=Noise, y = AvgC), colour=clusterCat) + geom_point(inherit.aes = FALSE, aes_string(color=clusterCat, size=sizeToUse))
clusterCat 是 df2 数据框中的一列,但 sizeToUse 是一个单独声明的变量,并且不是向量值。有没有一种方法可以将一个列的一个变量传递给数据框,并将另一个在更高环境中存在的变量传递给ggplot中的aes?我意识到我可以将 sizeToUse 添加为 df2 中的列,但这似乎效率很低。
那里发生了一些奇怪的事情 - 如果您发布 df2
的示例(尝试 dput(head(df2))
),我们会更容易回答。
但是你想做的事情是绝对允许的。试试这个代码:
sizeToUse <- length(unique(df2$Cluster))
ggplot(df2, aes(x = Noise, y = AvgC)) +
geom_point(aes(color = clusterCat), size = sizeToUse)
一些注意事项:
- 我让你的
sizeToUse
计算更简单一些 - 希望这是正确的
- 如果是单个值则不需要映射
sizeToUse
可以尝试在geom_point
中直接定义变量sizeToUse
如
ggplot(df2, aes(x=Noise, y = AvgC), colour=clusterCat) + geom_point(inherit.aes = FALSE, aes_string(color=clusterCat, size=eval(length(levels(factor(Cluster))))))
我将其作为 RShiny 应用程序的一部分:
sizeToUse = eval(length(levels(factor(df2$Cluster))))
ggplot(df2, aes(x=Noise, y = AvgC), colour=clusterCat) + geom_point(inherit.aes = FALSE, aes_string(color=clusterCat, size=sizeToUse))
clusterCat 是 df2 数据框中的一列,但 sizeToUse 是一个单独声明的变量,并且不是向量值。有没有一种方法可以将一个列的一个变量传递给数据框,并将另一个在更高环境中存在的变量传递给ggplot中的aes?我意识到我可以将 sizeToUse 添加为 df2 中的列,但这似乎效率很低。
那里发生了一些奇怪的事情 - 如果您发布 df2
的示例(尝试 dput(head(df2))
),我们会更容易回答。
但是你想做的事情是绝对允许的。试试这个代码:
sizeToUse <- length(unique(df2$Cluster))
ggplot(df2, aes(x = Noise, y = AvgC)) +
geom_point(aes(color = clusterCat), size = sizeToUse)
一些注意事项:
- 我让你的
sizeToUse
计算更简单一些 - 希望这是正确的 - 如果是单个值则不需要映射
sizeToUse
可以尝试在geom_point
中直接定义变量sizeToUse
如
ggplot(df2, aes(x=Noise, y = AvgC), colour=clusterCat) + geom_point(inherit.aes = FALSE, aes_string(color=clusterCat, size=eval(length(levels(factor(Cluster))))))