问题描述
我有两个向量.我想制作第一个向量的条形图(足够简单,正确).扭曲之处在于,第二个向量的每个元素都是第一个向量的每个元素的标准偏差(它本身是其他4个值的平均值).我该怎么办?
I have two vectors. I want to make a barplot of the first vector (simple enough, right). The twist is that every element of the second vector is the standard deviation for every element of the first vector (which itself is the average of 4 other values). How can I do that?
有问题的载体:
-4.6521175 0.145839723
1.1744100 0.342278694
-0.2581400 0.003776341
-0.3452675 0.073241199
-2.3823650 0.095008502
0.5625125 0.021627196
即,如何将第二列向量的元素作为误差线添加到第一列向量中的相应元素?
I.e., how can I add the elements of the second column vector as error bars to the corresponding elements in the first column vector?
注意:,在您询问之前,是的,我确实在该网站上进行了广泛的搜索,并且进行了大量的谷歌搜索,但是我的问题更加具体,即我发现的内容与我的不匹配需要.
Note: Before you ask, yes I did search extensively on this site and did a lot of googling, but my problem is a bit more specific, i.e. what I found didn't match what I needed.
推荐答案
使用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()
这导致:
如果要删除x轴上的数字,可以添加:
If you want to remove the numbers on the x-axis, you can add:
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
输入您的ggplot代码.
to your ggplot code.
使用的数据:
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)
为响应您的评论,这是您遇到的两种可能的解决方案要绘制这么多的条形图:
In response to your comment, two possible solution when you want plot such a large number of bars:
1::仅包括选择的轴标签:
1: Only include a selection of the axis-labels:
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))
这给出了:
可以看出,在图中填充如此多的条形图并不理想.因此,请参见备选方案2.
As can be seen, it is not ideal to cram so many bars in a plot. See therefore alternative 2.
2 :创建可用于创建构面的分组变量:
2: Create a grouping variable which you can use for creating facets:
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))
这给出了:
最后两个示例使用的数据:
Used data for the two last examples:
df2 <- data.frame(V1=sample(df$V1, 200, replace=TRUE),
V2=sample(df$V2, 200, replace=TRUE))
这篇关于将误差线添加到条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!