“为"循环只添加最后的 ggplot 层 [英] "for" loop only adds the final ggplot layer

查看:17
本文介绍了“为"循环只添加最后的 ggplot 层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

总结:当我使用for"循环向小提琴图(在 ggplot 中)添加图层时,唯一添加的图层是由最终循环迭代创建的图层.然而,在模仿循环将产生的代码的显式代码中,添加了所有层.

Summary: When I use a "for" loop to add layers to a violin plot (in ggplot), the only layer that is added is the one created by the final loop iteration. Yet in explicit code that mimics the code that the loop would produce, all the layers are added.

详细信息:我正在尝试创建具有重叠层的小提琴图,以显示按地点分层的几个调查问题响应的估计分布重叠或不重叠的程度.我希望能够包含任意数量的位置,因此我在每个位置的数据框中有一列,并尝试使用for"循环为每个位置生成一个 ggplot 层.但循环只添加循环最后一次迭代中的层.

Details: I am trying to create violin graphs with overlapping layers, to show the extent that estimate distributions do or do not overlap for several survey question responses, stratified by place. I want to be able to include any number of places, so I have one column in by dataframe for each place, and am trying to use a "for" loop to generate one ggplot layer per place. But the loop only adds the layer from the loop's final iteration.

这段代码说明了这个问题,以及一些失败的建议方法:

This code illustrates the problem, and some suggested approaches that failed:

library(ggplot2) 

# Create a dataframe with 500 random normal values for responses to 3 survey questions from two cities
topic <- c("Poverty %","Mean Age","% Smokers")
place <- c("Chicago","Miami")
n <- 500
mean <- c(35,  40,58,  50, 25,20)
var  <- c( 7, 1.5, 3, .25, .5, 1)
df <- data.frame( topic=rep(topic,rep(n,length(topic)))
                 ,c(rnorm(n,mean[1],var[1]),rnorm(n,mean[3],var[3]),rnorm(n,mean[5],var[5]))
                 ,c(rnorm(n,mean[2],var[2]),rnorm(n,mean[4],var[4]),rnorm(n,mean[6],var[6]))
                )
names(df)[2:dim(df)[2]] <- place  # Name those last two columns with the corresponding place name.
head(df) 

# This "for" loop seems to only execute the final loop (i.e., where p=3)
g <- ggplot(df, aes(factor(topic), df[,2]))
for (p in 2:dim(df)[2]) {
  g <- g + geom_violin(aes(y = df[,p], colour = place[p-1]), alpha = 0.3)
}
g

# But mimicing what the for loop does in explicit code works fine, resulting in both "place"s being displayed in the graph.
g <- ggplot(df, aes(factor(topic), df[,2]))
g <-   g + geom_violin(aes(y = df[,2], colour = place[2-1]), alpha = 0.3)
g <-   g + geom_violin(aes(y = df[,3], colour = place[3-1]), alpha = 0.3)
g

## per http://stackoverflow.com/questions/18444620/set-layers-in-ggplot2-via-loop , I tried 
g <- ggplot(df, aes(factor(topic), df[,2]))
for (p in 2:dim(df)[2]) {
  df1 <- df[,c(1,p)]
  g <- g + geom_violin(aes(y = df1[,2], colour = place[p-1]), alpha = 0.3)
}
g
# but got the same undesired result

# per http://stackoverflow.com/questions/15987367/how-to-add-layers-in-ggplot-using-a-for-loop , I tried
g <- ggplot(df, aes(factor(topic), df[,2]))
for (p in names(df)[-1]) {
  cat(p,"
")
  g <- g + geom_violin(aes_string(y = p, colour = p), alpha = 0.3)  # produced this error: Error in unit(tic_pos.c, "mm") : 'x' and 'units' must have length > 0
  # g <- g + geom_violin(aes_string(y = p            ), alpha = 0.3)  # produced this error: Error: stat_ydensity requires the following missing aesthetics: y
}
g
# but that failed to produce any graphic, per the errors noted in the "for" loop above

推荐答案

发生这种情况的原因是 ggplot 的懒惰评估".当以这种方式使用 ggplot 时,这是一个常见问题(在循环中单独制作层,而不是像 @hrbrmstr 的解决方案那样为您提供 ggplot ).

The reason this is happening is due to ggplot's "lazy evaluation". This is a common problem when ggplot is used this way (making the layers separately in a loop, rather than having ggplot to it for you, as in @hrbrmstr's solution).

ggplotaes(...) 的参数存储为 表达式,并且仅在渲染绘图时评估它们.所以,在你的循环中,像

ggplot stores the arguments to aes(...) as expressions, and only evaluates them when the plot is rendered. So, in your loops, something like

aes(y = df[,p], colour = place[p-1])

按原样存储,并在循环完成后渲染绘图时进行评估.此时,p=3,所以所有的图都用 p=3 渲染.

gets stored as is, and evaluated when you render the plot, after the loop completes. At this point, p=3 so all the plots are rendered with p=3.

因此,执行此操作的正确"方法是在 reshape2 包中使用 melt(...),以便将数据从宽格式转换为长格式,并且让 ggplot 为您管理图层.我将正确"放在引号中,因为在这种特殊情况下有一个微妙之处.当使用融化的数据框计算小提琴的分布时,ggplot 使用总计(芝加哥和迈阿密)作为尺度.如果您想要基于单独缩放的频率的小提琴,则需要使用循环(遗憾的是).

So the "right" way to do this is to use melt(...) in the reshape2 package so convert your data from wide to long format, and let ggplot manage the layers for you. I put "right" in quotes because in this particular case there is a subtlety. When calculating the distributions for the violins using the melted data frame, ggplot uses the grand total (for both Chicago and Miami) as the scale. If you want violins based on frequency scaled individually, you need to use loops (sadly).

解决惰性求值问题的方法是在data=... 定义中放置对循环索引的任何引用.这存储为表达式,实际数据存储在绘图定义中.所以你可以这样做:

The way around the lazy evaluation problem is to put any reference to the loop index in the data=... definition. This is not stored as an expression, the actual data is stored in the plot definition. So you could do this:

g <- ggplot(df,aes(x=topic))
for (p in 2:length(df)) {
  gg.data <- data.frame(topic=df$topic,value=df[,p],city=names(df)[p])
  g <- g + geom_violin(data=gg.data,aes(y=value, color=city))
}
g

它给出与你相同的结果.请注意,索引 p 不会出现在 aes(...) 中.

which gives the same result as yours. Note that the index p does not show up in aes(...).

更新:关于 scale="width" 的注释(在评论中提到).这导致所有小提琴具有相同的宽度(见下文),这与 OP 的原始代码中的缩放比例不同.IMO 这不是可视化数据的好方法,因为它表明芝加哥组中有更多数据.

Update: A note about scale="width" (mentioned in a comment). This causes all the violins to have the same width (see below), which is not the same scaling as in OP's original code. IMO this is not a great way to visualize the data, as it suggests there is much more data in the Chicago group.

ggplot(gg) +geom_violin(aes(x=topic,y=value,color=variable),
                        alpha=0.3,position="identity",scale="width")

这篇关于“为"循环只添加最后的 ggplot 层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆