Ste*_*fan 4 plot r vector bar-chart
我有两个向量.我想制作第一个矢量的条形图(简单,正确).扭曲是第二个向量的每个元素都是第一个向量的每个元素的标准偏差(它本身是4个其他值的平均值).我怎样才能做到这一点?
有问题的载体:
-4.6521175 0.145839723
1.1744100 0.342278694
-0.2581400 0.003776341
-0.3452675 0.073241199
-2.3823650 0.095008502
0.5625125 0.021627196
Run Code Online (Sandbox Code Playgroud)
即,如何将第二列向量的元素作为误差条添加到第一列向量中的相应元素?
注意:在你问之前,是的,我在这个网站上进行了大量搜索,并进行了大量的谷歌搜索,但我的问题更具体,即我发现的与我需要的不符.
S. *_*ica 11
我个人arrows()最喜欢这种图形:
df <- data.frame(bar = c(-4.6521175, 1.1744100, -0.2581400, -0.3452675, -2.3823650, 0.5625125),
error = c(0.145839723, 0.342278694, 0.003776341, 0.073241199, 0.095008502, 0.021627196))
foo <- barplot(df$bar,ylim=c(-6,2),border=NA)
arrows(x0=foo,y0=df$bar+df$error,y1=df$bar-df$error,angle=90,code=3,length=0.1)
Run Code Online (Sandbox Code Playgroud)
两个细节:
border=NA在barplot()删除条形周围的边框,所以你可以实际看到第三个条形图周围的错误胡须.由于第三个误差很小,所以晶须几乎位于条形边缘的顶部.
我使用length参数arrows()来减小水平胡须的宽度,如果我们有更多的条形,这尤其重要.默认是length=0.25.
但请注意,"炸药地块"有很大的缺点.您写道,您的数据仅来自每个条形的四个原始点.在这种情况下,只绘制原始数据的(抖动)点图几乎肯定会更好.
有一种实现geom_bar和geom_errorbar的ggplot2:
library(ggplot2)
ggplot(df, aes(x=row.names(df), y=V1)) +
geom_bar(stat="identity", fill="grey") +
geom_errorbar(aes(ymin = V1 - V2, ymax = V1 + V2), width=0.6) +
theme_classic()
Run Code Online (Sandbox Code Playgroud)
这导致:
如果要删除x轴上的数字,可以添加:
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
Run Code Online (Sandbox Code Playgroud)
你的ggplot代码.
使用数据:
df <- read.table(text="-4.6521175 0.145839723
1.1744100 0.342278694
-0.2581400 0.003776341
-0.3452675 0.073241199
-2.3823650 0.095008502
0.5625125 0.021627196", header=FALSE)
Run Code Online (Sandbox Code Playgroud)
为了回应你的评论,当你想要绘制如此大量的条形时,有两种可能的解决方案:
1:仅包括轴标签的选择:
ggplot(df2, aes(x=as.numeric(row.names(df2)), y=V1)) +
geom_bar(stat="identity", fill="grey", width=0.7) +
geom_errorbar(aes(ymin = V1 - V2, ymax = V1 + V2), width=0.5) +
scale_x_continuous(breaks=c(1,seq(10,200,10)), expand=c(0,0)) +
theme_classic() +
theme(axis.text.x=element_text(size = 6, angle = 90, vjust = 0.5))
Run Code Online (Sandbox Code Playgroud)
这给了:
可以看出,在情节中填充如此多的条形图是不理想的.因此,请参见替代方案
2:创建可用于创建构面的分组变量:
df2$id <- rep(letters[1:20], each=10)
ggplot(df2, aes(x=as.numeric(row.names(df2)), y=V1)) +
geom_bar(stat="identity", fill="grey", width=0.7) +
geom_errorbar(aes(ymin = V1 - V2, ymax = V1 + V2), width=0.5) +
scale_x_continuous(breaks=as.numeric(row.names(df2))) +
facet_wrap(~ id, scales = "free_x") +
theme_bw() +
theme(axis.text.x=element_text(angle = 90, vjust = 0.5))
Run Code Online (Sandbox Code Playgroud)
这给了:
最后两个示例使用的数据:
df2 <- data.frame(V1=sample(df$V1, 200, replace=TRUE),
V2=sample(df$V2, 200, replace=TRUE))
Run Code Online (Sandbox Code Playgroud)