强制误差条位于条形中间

时间:2015-06-27 20:05:12

标签: r ggplot2

我正在使用R和ggplot2绘制一个带有误差条的非常基本的条形图,但是我很难强迫它们位于我创建的条形图的中心。

我的代码如下:

library(ggplot2)


Type <- c("A", "A", "A", "B", "B", "B")
Time <- c(0, 24, 48, 0, 24, 48)
CellCount <- c(321,213,123,432,234,324)
Error <- c(12,32,12,34,23,21)
df <- data.frame(Type,Time,CellCount,Error)

p <- ggplot(df, aes(x=Time, y = CellCount, fill = Type)) + 
     geom_bar(stat = "identity", position = "dodge") + 
     xlab("Time (h)") + ylab("Cell count") + 
     scale_x_continuous(breaks = seq(0,48,24)) +
     scale_fill_discrete(labels = c("Anirridia", "Control")) + 
     guides(fill = guide_legend(title = NULL))

p + geom_errorbar(aes(ymin = CellCount - Error, 
                      ymax = CellCount + Error), 
                      width = 0.9, 
                      position = "dodge")

但这会产生以下情节:

enter image description here

误差条位于条形的边缘。我认为这是因为它们是在0,24和48小时的时间内绘制的,但我不知道如何将它们移动到每个栏的中心

请建议我如何“移动”错误栏

提前致谢

编辑:我以前看过这个链接的问题是重复的,但是当我添加

 p + geom_errorbar(aes(ymin = CellCount - Error, 
                  ymax = CellCount + Error), 
                  width = 0.9, 
                  position=position_dodge(.9))

我仍然得到与之前相同的情节

Edit2:我认为Rstudio可能存在问题吗?或者至少我的安装...因为我复制了粘贴代码中的“重复”问题,我得到了以下图表... http://imgur.com/H2DRvqg

2 个答案:

答案 0 :(得分:2)

虽然@ jeremycg的答案是正确的(对于ggplot主题系统的模糊知识+1),但它更多的是副作用而不是解决方案。

让我们想一下条形图的典型用例场景。通常,当我们尝试呈现以下数据时,我们会使用条形图:

  • 连续离散

目前,我们的数据是:

  • 连续连续

点图更适合此数据类型。但我们可以看到它看起来有点荒谬,因为我们的数据不是真正连续的。

ggplot(df, aes(Time,CellCount, color = Type)) + 
  geom_point(stat="identity") + 
  geom_errorbar(aes(
    ymin = CellCount - Error, 
    ymax = CellCount + Error),   
    width = 0.9)

对于这种性质的表示,应该使用分类变量作为x坐标。

这可以通过预处理变量Time,作为因子,或通过调用美学字符串(aes)中的变量as.factor来实现。

ggplot(df, aes(
    x=as.factor(Time), # as.factor() makes this a discrete scale
    y = CellCount, 
    fill = Type)) +
  geom_bar(stat = "identity", position = "dodge") +
  geom_errorbar(aes(
    ymin = CellCount - Error, 
    ymax = CellCount + Error),   
    width = 0.9, 
    position = position_dodge(width = 0.9)) + # now you can use it
  labs(x= "Time (h)", y = "Cell count") +
  scale_fill_discrete(labels = c("Anirridia", "Control")) 

答案 1 :(得分:1)

你的酒吧宽10.8个单位(每个12个单位,差距为0.9),所以试试:

position = position_dodge(10.8*2)
geom_errorbar来电