我试图将数据(见下文)绘制为分组条形图。我已在此处按照其他建议更改position = ""
中的geom_bar
,但我似乎无法使其正常运行。我得到的只是一个堆积条形图。这是我最近的尝试:
ggplot(data = IFNg, aes(x = IFNg$Location, y = IFNg$`Fold Change`)) +
geom_bar(position = 'identity', stat = "identity", fill = IFNg$Day) +
ylab("Fold Change (log_2)") + geom_errorbar(limits, width=0.15)
我也尝试了以下内容,这也会产生叠加图,但这个图的颜色不同:
ggplot(data = IFNg, aes(x = IFNg$Location, y = IFNg$`Fold Change`,
fill= IFNg$Day)) + geom_bar(position = 'identity', stat = "identity") +
ylab("Fold Change (log_2)") + geom_errorbar(limits, width=0.15)
这是我的其余代码中的数据:
dat <- structure(list(Day = c(1L, 3L, 7L, 21L, 1L, 3L, 7L, 21L, 1L,
3L, 7L, 21L), Order = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L,
3L, 3L), Target = c("IFN-g", "IFN-g", "IFN-g", "IFN-g", "IFN-g",
"IFN-g", "IFN-g", "IFN-g", "IFN-g", "IFN-g", "IFN-g", "IFN-g"),
Location = c("Duodenum", "Duodenum", "Duodenum", "Duodenum",
"Duodenum (Lymph)", "Duodenum (Lymph)", "Duodenum (Lymph)",
"Duodenum (Lymph)", "Proximal Jejunum", "Proximal Jejunum",
"Proximal Jejunum", "Proximal Jejunum"), `Fold Change` = c(-1.750896098,
-2.194886907, -0.838822724, 0.680612172, -0.375563984, 0.650154987,
0.844897327, -0.228441603, -1.298230671, -1.173634963, -1.877736135,
0.787322978), StDev = c(0.027477611, 0.029974897, 0.19025044, 1.235986647,
0.055798435, 0.086102327, 0.115422155, 0.34470734, 0.020947691, 0.165294027,
0.040111751, 0.035010207)), .Names = c("Day", "Order", "Target", "Location",
"Fold Change", "StDev"), class = c("tbl_df", "data.frame"), row.names = c(NA,-12L))
IFNg <- dat[dat$Target == 'IFN-g', ]
limits <- aes(ymax = IFNg$`Fold Change` + IFNg$StDev,
ymin = IFNg$`Fold Change` - IFNg$StDev)
答案 0 :(得分:6)
您的大多数问题都来自于您输入的内容,例如data$column
而不是column
。此外,您的Day
是数字,但由Day
定义不同的并排条形,它必须是离散的(因子)。
我还想指出?geom_bar
帮助页面并不长,并且有这段话:
默认情况下,同一位置发生的多个x将按
position_stack
堆叠在一起。如果您希望将它们并排躲避,请参阅?position_dodge
。最后,position_fill
通过堆叠条形图然后拉伸或挤压到相同的高度来显示每个x的相对比例。
通常情况下,position = 'dodge'
可以正常工作,但会让人感到困惑,并认为你的错误栏宽度是这种情况下要避开的宽度,所以我们将使用完整的position = position_dodge()
:< / p>
# No data$ inside aes()!!!
limits <- aes(ymax = `Fold Change` + StDev,
ymin = `Fold Change` - StDev)
ggplot(data = IFNg,
# group lets `ggplot` know we want different errorbars/bars for each day
aes(x = Location, y = `Fold Change`, group = factor(Day))
) +
geom_bar(
stat = "identity",
aes(fill = factor(Day)),
position = position_dodge(width = 0.9)
) +
ylab("Fold Change (log_2)") +
geom_errorbar(
limits,
width = 0.15,
position = position_dodge(width = 0.9)
)