简体   繁体   English

组之间的ggplot差异

[英]ggplot differences between groups

I have a df with groups in different trials, and I want to make a bar graph of just deltas between trials in ggplot. 我有一个包含不同试验组的df,并且我想制作一个仅显示ggplot中试验之间的增量的条形图。 Having a hard time getting ggplot to understand I want the differences in one df. 很难让ggplot理解我想要一个df中的差异。 Also, some of the treatments aren't represented in the second trial, so I want to just count that as 0 (ie delta would be = trial 1 - 0). 另外,某些治疗方法未在第二次试验中得到体现,因此我只想将其计为0(即,增量为=试验1-0)。

 set.seed(1)

 df <- data.frame((matrix(nrow=175,ncol=4)))
 colnames(df) <- c("group","trial","count","hour")
 df$group <- rep(c("A","B","C","D","A","B","D"),each=25)
 df$trial <- rep(c(rep(1,times=100),rep(2,times=75)))
 df$count <- runif(175,0,50)
 df$hour <- rep(1:25,times=7)


 df2 <- aggregate(df[,3:4],list(df$group,df$trial),mean)
 colnames(df2)[1:2] <- c("group","trial") 

That's where I've gotten to. 那就是我要去的地方。 I have plotted with individual bars for (group*trial), but I can't figure out how to subtract them. 我已经为(group * trial)绘制了单独的条形图,但是我不知道如何减去它们。 I want a plot of x=group and y= delta(trial). 我想要x = group和y = delta(trial)的图。

I tried this: 我尝试了这个:

 ggplot(df2 %>% group_by(group) %>% delta=diff(count),
   aes(x=group,y=delta)) + geom_bar()

from a similar posting I came across, but no luck. 我遇到过类似的帖子,但没有运气。

this should do the trick: 这应该可以解决问题:

ggplot(df2 %>% group_by(group) %>% summarise(delta=ifelse(nrow(.)>1,diff(count),0)),
       aes(x=group,y=delta)) + geom_col()#geom_bar(stat="identity")

The problems are, that "diff" returns not the value 0 but a vector of length 0, when there is only one input value. 问题是,当只有一个输入值时,“ diff”返回的不是值0而是一个长度为0的向量。 Also instead of using geom_bar , I recommend geom_col . 另外,我建议geom_col使用geom_bar ,而是建议使用geom_col Another thing, you should think about, is that the diff result is depending on the order of your data frame. 您应该考虑的另一件事是,差异结果取决于数据帧的顺序。 As such I would recommend to use 因此,我建议使用

ggplot(df2 %>% group_by(group) %>% summarise(delta_trial_1_trial_2=
                                           ifelse(length(trial)>1,
                                                  count[trial==2]-count[trial==1],0)),
   aes(x=group,y=delta_trial_1_trial_2)) + geom_col()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM