【问题标题】:Barplot with continuous x axis using base r graphics使用基本 r 图形的具有连续 x 轴的条形图
【发布时间】:2015-04-22 10:46:54
【问题描述】:

我希望将条形图上的 x 轴按时间缩放,以便准确表示进行测量的时间。

我有这些数据框:

    > Botcv
        Date Average       SE
1 2014-09-01     4.0 1.711307
2 2014-10-02     5.5 1.500000

> Botc1
        Date Average        SE
1 2014-10-15   2.125 0.7180703
2 2014-11-12   1.000 0.4629100
3 2014-12-11   0.500 0.2672612

> Botc2
        Date Average        SE
1 2014-10-15   3.375 1.3354708
2 2014-11-12   1.750 0.4531635
3 2014-12-11   0.625 0.1829813

我使用此代码生成分组条形图:

covaverage <- c(Botcv$Average,NA,NA,NA)
c1average <- c(NA,NA, Botc1$Average)
c2average <- c(NA,NA, Botc2$Average)
date <- c(Botcv$Date, Botc1$Date)

averagematrix <- matrix(c(covaverage,c1average, c2average), nrow=3, ncol=5, byrow=TRUE)

barplot(averagematrix,date, xlab="Date", ylab="Average", axis.lty=1, space=NULL,width=3,beside=T, ylim=c(0.00,6.00))

R 默认情况下将条形图等距离绘制出来,我一直在尝试找到解决方法。我见过其他几个使用 ggplot2 的解决方案,但我正在为我的硕士论文制作绘图,并希望让我的条形图的外观与我使用基本 R 图形创建的其他图表保持一致。我还想在图中添加误差线。如果有人能提供解决方案,我将不胜感激!!谢谢!

【问题讨论】:

    标签: r bar-chart


    【解决方案1】:

    也许您可以以此为起点。使用箱线图可能更容易,因为可以使用 at 参数将它们放在给定的 x 位置。对于基本条形图,这是无法做到的,但您可以使用 rectangle 代替复制 barplot 外观。可以使用arrowssegments 添加误差线。

    bar_w = 1 # width of bars
    offset = c(-1,1) # offset to avoid overlapping
    cols = grey.colors(2) # colors for different types
    
    # combine into a single data frame
    d = data.frame(rbind(Botc1, Botc2), 'type' = c(1,1,1,2,2,2))
    
    # set up empty plot with sensible x and y lims
    plot(as.Date(d$Date), d$Average, type='n', ylim=c(0,4))
    
    # draw data of data frame 1 and 2
    for (i in unique(d$type)){
    
        dd = d[d$type==i, ]
        x = as.Date(dd$Date)
        y = dd$Average
    
        # rectangles
        rect(xleft=x-bar_w+offset[i], ybottom=0, xright=x+bar_w+offset[i], ytop=y, col=cols[i])
        # errors bars
        arrows(x0=x+offset[i], y0=y-0.5*dd$SE, x1=x+offset[i], y1=y+0.5*dd$SE, col=1, angle=90, code=3, length = 0.1)
    }
    

    【讨论】:

      【解决方案2】:

      如果您想要获得的只是与基本主题相匹配的主题,ggplot2 中的 + theme_bw() 将实现此目的:

      data(mtcars)
      require(ggplot2)
      ggplot(mtcars, aes(factor(cyl), mpg)) +
          geom_boxplot() + 
          theme_bw()
      

      结果

      替代方案

      boxplot(mpg~cyl,data=mtcars)
      

      如果,正如您所说,您唯一想要实现的是相似的外观,并且您在 ggplot2 中有工作图,使用 theme_bw() 应该产生与通过标准绘图得出的图无法区分的图机制。如果您愿意,可以调整一些细节,例如字体大小、图形边框的粗细或异常值的可视化。

      【讨论】:

        猜你喜欢
        • 2018-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-08
        相关资源
        最近更新 更多