[英]Adding set column values as min/max error bars on R
Apologies if this has been asked before, but it is difficult to articulate in order to find an answer. 抱歉,是否曾经有人问过这个问题,但是很难找到答案。
I have the following set of data below. 我下面有以下数据集。 In R, I would like to construct a bar plot for
PV1
and PV2
for AvgRead
and AvgUniq
. 在R中,我想为
AvgRead
和AvgUniq
构造PV1
和PV2
的AvgUniq
。 For the error bars, I would like to set MinRead
and MinUniq
as the minima, and MaxRead
and MaxUniq
as the maxima. 对于误差线,我想将
MinRead
和MinUniq
设置为最小值,将MaxRead
和MaxUniq
为最大值。
If you could help that would be greatly appreciated. 如果您能提供帮助,将不胜感激。 Again my apologies if this has been asked before.
再次道歉,如果以前已经问过这个问题。
AvgRead MinRead MaxRead AvgUniq MinUniq MaxUniq
PV1 20 10 40 40 20 80
PV2 40 20 80 80 40 160
You need to reshape your data a little bit using the melt()
and dcast()
functions from reshape2
: 您需要使用
dcast()
的melt()
和dcast()
函数对数据进行一些reshape2
:
library(reshape2)
library(ggplot2)
df <- data.frame(
row.names = c("PV1", "PV2"),
AvgRead = c(20, 40),
MinRead = c(10, 20),
MaxRead = c(40, 80),
AvgUniq = c(40, 80),
MinUniq = c(20, 40),
MaxUniq = c(70, 160)
)
df$name <- row.names(df)
df_molten <- melt(df)
df_molten$var1 <- substr(df_molten$variable, 1, 3)
df_molten$var2 <- substr(df_molten$variable, 4, 10000)
df_cast <- dcast(df_molten, name + var2 ~ var1, value.var = "value")
ggplot(data = df_cast, aes(x = name, y = Avg, fill = var2)) +
geom_bar(stat = "identity", position = "dodge") +
geom_errorbar(
aes(ymin = Min, ymax = Max),
width = 0.5,
size = 1.3,
position = position_dodge(0.9)
)
EDIT: to change the order of the bars you need to change var2 to factors and sort the levels accordingly: 编辑:要更改条形的顺序,您需要将var2更改为因子并相应地对级别进行排序:
df_cast <- dcast(df_molten, name + var2 ~ var1, value.var = "value")
df_cast$var2 <- factor(df_cast$var2, levels = c("Uniq", "Read"))
ggplot(data = df_cast, aes(x = name, y = Avg, fill = var2)) +
geom_bar(stat = "identity", position = "dodge") +
geom_errorbar(
aes(ymin = Min, ymax = Max),
width = 0.5,
size = 1.3,
position = position_dodge(0.9)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.