R中的ggplot2 barplot与分组列,如何取消堆叠?

Jam*_*ade 3 r bar-chart ggplot2

我正在尝试将数据(见下文)绘制为分组条形图.我已经按照其他建议改变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)
Run Code Online (Sandbox Code Playgroud)

我也试过以下也会产生叠加图,但是这个图的颜色不同:

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这是我的其余代码与数据:

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)
Run Code Online (Sandbox Code Playgroud)

Gre*_*gor 6

你的大部分问题都来自于你不应该输入的东西,data$column而不是column.此外,您Day是数字,但要定义不同的并排条Day,它需要是离散的(因子).

我还想指出?geom_bar帮助页面不是那么长,并且有这个段落:

默认情况下,在同一位置发生的多个x将叠加在一起position_stack.如果你想让它们被左右躲闪,请参阅?position_dodge.最后,position_fill通过堆叠条,然后拉伸或挤压到相同的高度,显示每个x的相对比例.

通常,position = 'dodge'工作得很好,但它会混淆并认为你的错误栏宽度是在这种情况下闪避的宽度,所以我们将使用完整position = position_dodge():

# 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)
    )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述