奇怪的行为ggplot2

奇怪的行为ggplot2

本文介绍了奇怪的行为ggplot2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我只想使用ggplot2在散点图上绘制多个箭头。在这个(虚拟)例子中,绘制了一个箭头,但它随着i的递增而移动,并且只绘制一个箭头。为什么会发生这种情况? library(ggplot2)a b for(i in 1:nrow(b)){a mapping = aes(x = b [i,1 ],y = b [i,2],xend = b [i,3],yend = b [i,4])) plot(a)} 感谢。 并不奇怪的行为,这正是应该如何工作 aes()。它会延迟评估参数,直到绘图实际运行。如果你在data.frame之外的变量中包含表达式(比如 i )和函数(比如 [,] )。这些仅在实际绘制情节时被消除。 如果您想强制推断参数,可以使用 aes _ 。这对你是有用的 $ b $ pre $ for(i in 1:nrow(b)){a mapping = aes_(x = b [i,1],y = b [i,2],xend = b [i,3],yend = b [i,4 ])) plot(a) 现在在循环中在环境中评估 x = 和 y = 等参数,并且它们的值在图层中冻结 。 当然,最好不要在循环中构建图层,只需按照@ eipi10的回答指出正确的数据对象。 I simply want to draw multiple arrows on a scatterplot using ggplot2. In this (dummy) example, an arrow is drawn but it moves as i is incremented and only one arrow is drawn. Why does that happen?library(ggplot2)a <- ggplot(mtcars, aes(wt, mpg)) + geom_point()b <- data.frame(x1=c(2,3),y1=c(10,10),x2=c(3,4),y2=c(15,15))for (i in 1:nrow(b)) { a <- a + geom_segment(arrow=arrow(), mapping = aes(x=b[i,1],y=b[i,2],xend=b[i,3],yend=b[i,4])) plot(a) }Thanks. 解决方案 This isn't strange behavior, this is exactly how aes() is supposed to work. It delays evaluation of the parameters until the plotting actually runs. This is problematic if you include expressions to variable outside your data.frame (like i) and functions (like [,]). These are only evaulated when you actually "draw" the plot.If you want to force evaulation of your parameters, you can use aes_. This will work for youfor (i in 1:nrow(b)) { a <- a + geom_segment(arrow=arrow(), mapping = aes_(x=b[i,1],y=b[i,2],xend=b[i,3],yend=b[i,4])) }plot(a)Now within the loop the parameters for x= and y=, etc are evaluated in the environment and their value are "frozen" in the layer.Of course, it would be better not to build layers in loops and just procide a proper data object as pointed out in @eipi10's answer. 这篇关于奇怪的行为ggplot2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 20:35