r - 在 ggplot barplot 中添加自定义行

标签 r ggplot2 bar-chart lines

我创建了这个情节 enter image description here

使用此代码:

ggplot(data_long, aes(Trial,value,fill=factor(Trial))) +    
    stat_summary(fun.y=mean,geom="bar") + facet_grid(Task~Gruppo) + labs(x="Trial 
    type",y="Accuracy %") + theme(legend.position="none")

现在,我需要添加自定义行来显示两个值之间的差异。这是我想要做的示例(请参阅 p = 0.46 的前两个条形图):

enter image description here

我不知道解决方案,而且自从我使用facet_grid以来,事情对我来说也更加复杂。 谁能帮我吗?

最佳答案

首先,由于未提供示例数据,因此制作了我自己的示例数据。这些数据已经汇总(每个级别组合只有一个值。

set.seed(1)
df<-data.frame(expand.grid(c("Control","Effect"),c("Self","Other"),c("Type1","Type2")),
     runif(8,0,1))
colnames(df)<-c("Treatment","Group","Type","value")
df
  Treatment Group  Type     value
1   Control  Self Type1 0.2655087
2    Effect  Self Type1 0.3721239
3   Control Other Type1 0.5728534
4    Effect Other Type1 0.9082078
5   Control  Self Type2 0.2016819
6    Effect  Self Type2 0.8983897
7   Control Other Type2 0.9446753
8    Effect Other Type2 0.6607978

现在您需要为行的位置添加两个新值。 ymin 值是原始值加上小常数。为每个方面计算 ymax 值(使用 TreatmentType 作为分组),它是方面中的最大值加上一些常数。

library(plyr)
df<-ddply(df,.(Treatment,Type),transform,ymax=max(value)+0.2)
df$ymin<-df$value+0.05
df
  Treatment Group  Type     value      ymax      ymin
1   Control  Self Type1 0.2655087 0.7728534 0.3155087
2   Control  Self Type2 0.2016819 1.1446753 0.2516819
3   Control Other Type1 0.5728534 0.7728534 0.6228534
4   Control Other Type2 0.9446753 1.1446753 0.9946753
5    Effect  Self Type1 0.3721239 1.1082078 0.4221239
6    Effect  Self Type2 0.8983897 1.0983897 0.9483897
7    Effect Other Type1 0.9082078 1.1082078 0.9582078
8    Effect Other Type2 0.6607978 1.0983897 0.7107978

第二个数据框是为标签制作的。这里,每个方面的 y 位置都是原始的 ymax 值加上一些常量,并且 lab 包含您需要显示的标签。

df.names<-ddply(df,.(Treatment,Type),summarise,ymax=ymax[1]+0.1)
df.names$lab<-c("p=0.46","**","***","*")
df.names
  Treatment  Type      ymax    lab
1   Control Type1 0.8728534 p=0.46
2   Control Type2 1.2446753     **
3    Effect Type1 1.2082078    ***
4    Effect Type2 1.1983897      *

现在 df 已经是汇总值,使用 geom_bar(stat="identity") 而不是 stat_summary()。通过两次 geom_segment() 调用添加其他线条 - 第一个绘制垂直线,第二个添加水平线。 geom_text() 在线条上方添加标签。

ggplot(df, aes(Group,value,fill=Group)) +    
  geom_bar(stat="identity") + facet_grid(Type~Treatment) + 
  theme(legend.position="none")+
  geom_segment(aes(x=Group,xend=Group,y=ymin,yend=ymax))+
  geom_segment(aes(x="Self",xend="Other",y=ymax,yend=ymax))+
  geom_text(data=df.names,aes(x=1.5,y=ymax,label=lab),inherit.aes=FALSE)

enter image description here

关于r - 在 ggplot barplot 中添加自定义行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19000494/

相关文章:

r - 具有置信区间的箱线图并识别 r 中的特定数据点

ios - 如何更改 ios-charts 中的气球标记图像?

r - ggplot2 中多面分组条形图的不同颜色阴影

r - 文件不存在时如何退出downloadHandler

r - 将列并行分配给 data.table

R用ggmap对象叠加geom_polygon,空间文件转换

r - 如何使用dplyr按行求和n个最高值而不 reshape ?

r - ggplot facet_wrap 选定的 data.frame 列?

r - `data` 必须是一个数据框,或者其他被 `fortify()` 强制的对象,而不是一个带有 ranger 类的 S3 对象

r - 如何在barplot中获取条形的x坐标