ggplot2:为每组平均添加一行 [英] ggplot2: add line for average per group

查看:102
本文介绍了ggplot2:为每组平均添加一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  library(ggplot2)

orderX <-c(A= 1,B= 2,C= 3)
y< - rnorm(20)
x< - as.character(1:20)
group< -c(rep(A,5),rep(B,7 ),rep(C,5),rep(A,3))
df < - data.frame(x,y,group)
df $ lvls < - as。数字(orderX [df $ group])

ggplot(data = df,aes(x = reorder(df $ x,df $ lvls),y = y))+
geom_point aes(color = group))+
geom_line(stat =hline,yintercept =mean,aes(color = group))

我想创建一个如下图:



当我不需要对X的值进行重新排序时,这确实有效,但是,当我使用重新排序时,它不会工作了。

解决方案

从ggplot2 2.x开始,这种方法不幸中断了。



以下代码正好提供了我想要的内容,并提供了一些额外的计算:

  library(ggplot2)
library(data.table)

orderX< - c(A = 1,B= 2,C= 3)
y < - rnorm(20)
x < - as.character(1:20)
group < c(rep(A,5),rep(B,7),rep(C,5),rep(A,3))
dt < - data.table x,y,group)
dt [,lvls:= as.numeric(orderX [group])]
dt [,average:= mean(y),by = group]
dt [,x:= reorder(x,lvls)]
dt [,xbegin:= names(attr(dt $ x,scores)== unique(lvls)))[1],by =组]
dt [,xend:= names(which(attr(dt $ x,scores)== unique(lvls)))[length(x)],by = group]

ggplot(data = dt,aes(x = x,y = y))+
geom_point(aes(color = group))+
facet_grid(。〜group,space =free ,scale =free_x)+
geom_segment(aes(x = xbegin,xend = xend,y = average,yend = average,group = group,color = group))

$ b


library(ggplot2)

orderX <- c("A" = 1, "B" = 2, "C" = 3)
y <- rnorm(20)
x <- as.character(1:20)
group <- c(rep("A", 5), rep("B", 7), rep("C", 5), rep("A", 3))
df <- data.frame(x, y, group)
df$lvls <- as.numeric(orderX[df$group])

ggplot(data = df, aes(x=reorder(df$x, df$lvls), y=y)) + 
geom_point(aes(colour = group)) + 
geom_line(stat = "hline", yintercept = "mean", aes(colour = group))

I want to create a graph like this:

This does work, when I do not need to reorder the values of X, however, when I do use reorder, it doesn't work anymore.

解决方案

As of ggplot2 2.x this approach is unfortunately broken.

The following code provides exactly what I wanted, with some extra calculations up front:

library(ggplot2)
library(data.table)

orderX <- c("A" = 1, "B" = 2, "C" = 3)
y <- rnorm(20)
x <- as.character(1:20)
group <- c(rep("A", 5), rep("B", 7), rep("C", 5), rep("A", 3))
dt <- data.table(x, y, group)
dt[, lvls := as.numeric(orderX[group])]
dt[, average := mean(y), by = group]
dt[, x := reorder(x, lvls)]
dt[, xbegin := names(which(attr(dt$x, "scores") == unique(lvls)))[1], by = group]
dt[, xend := names(which(attr(dt$x, "scores") == unique(lvls)))[length(x)], by = group]

ggplot(data = dt, aes(x=x, y=y)) + 
    geom_point(aes(colour = group)) +
    facet_grid(.~group,space="free",scales="free_x") + 
    geom_segment(aes(x = xbegin, xend = xend, y = average, yend = average, group = group, colour = group))

The resulting image:

这篇关于ggplot2:为每组平均添加一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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