【问题标题】:Barplot with multiple columns in RR中具有多列的条形图
【发布时间】:2016-10-22 05:29:36
【问题描述】:

R 新手并试图找出条形图。
我正在尝试在 R 中创建一个条形图,显示来自按第三列分组的 2 列的数据。

数据帧名称:SprintTotalHours

包含数据的列:

OriginalEstimate,TimeSpent,Sprint
178,471.5,16.6.1
210,226,16.6.2
240,195,16.6.3

我想要一个条形图,在每个 sprint 的 TimeSpent 旁边显示 OriginalEstimate。 我试过了,但没有得到我想要的:

colours = c("red","blue")

barplot(as.matrix(SprintTotalHours),main='Hours By Sprint',ylab='Hours', xlab='Sprint' ,beside = TRUE, col=colours)

abline(h=200)

我想使用基本图形,但如果无法完成,我不反对在必要时安装软件包。

【问题讨论】:

    标签: r charts bar-chart


    【解决方案1】:

    你需要融化成长形,这样你才能分组。虽然您可以在基础 R 中执行此操作,但没有多少人这样做,尽管有多种软件包选项(此处为 tidyr)。同样,ggplot2 可以让您以更少的工作获得更好的结果,这也是大多数人最终会采用的绘图方式:

    library(tidyr)
    library(ggplot2)
    
    ggplot(data = SprintTotalHours %>% gather(Variable, Hours, -Sprint), 
           aes(x = Sprint, y = Hours, fill = Variable)) + 
        geom_bar(stat = 'identity', position = 'dodge')
    

    如果您愿意,可以使用基本 R,但这种方法(或多或少)是目前的传统方法。

    【讨论】:

      【解决方案2】:

      使用基础 R:

      DF  <- read.csv(text=
      "OriginalEstimate,TimeSpent,Sprint
      178,471.5,16.6.1
      210,226,16.6.2
      240,195,16.6.3")
      
      # prepare the matrix for barplot
      # note that we exclude the 3rd column and we transpose the data
      mx <- t(as.matrix(DF[-3]))
      colnames(mx) <- DF$Sprint
      
      colours = c("red","blue")
      # note the use of ylim to give 30% space for the legend
      barplot(mx,main='Hours By Sprint',ylab='Hours', xlab='Sprint',beside = TRUE, 
              col=colours, ylim=c(0,max(mx)*1.3))
      # to add a box around the plot
      box()
      
      # add a legend
      legend('topright',fill=colours,legend=c('OriginalEstimate','TimeSpent'))
      

      【讨论】:

      • 很好的答案,按预期工作并且喜欢这些笔记。我结合使用了这个答案和来自 bgoldst 的答案来获得我想要的外观。最终选择 bgoldst,因为他与我的油漆示例的外观和感觉相匹配。但是,我更喜欢这个的外观,所以我也从这里获取了一些代码。谢谢!
      • 很高兴能帮上忙 :)
      【解决方案3】:

      cols <- c('red','blue');
      ylim <- c(0,max(SprintTotalHours[c('OriginalEstimate','TimeSpent')])*1.8);
      par(lwd=6);
      barplot(
          t(SprintTotalHours[c('OriginalEstimate','TimeSpent')]),
          beside=T,
          ylim=ylim,
          border=cols,
          col='white',
          names.arg=SprintTotalHours$Sprint,
          xlab='Sprint',
          ylab='Hours',
          legend.text=c('Estimated','TimeSpent'),
          args.legend=list(text.col=cols,col=cols,border=cols,bty='n')
      );
      box();
      

      数据

      SprintTotalHours <- data.frame(OriginalEstimate=c(178L,210L,240L),TimeSpent=c(471.5,226,
      195),Sprint=c('16.6.1','16.6.2','16.6.3'),stringsAsFactors=F);
      

      【讨论】:

      • 我混合了这个答案和来自 digEmAll 的答案以获得我想要的外观。这最终是我的选择,因为它看起来就像我的蹩脚油漆图,所以符合要求!但是,我使用 digEmAll 的代码使它看起来更像他的,不知道我想要什么的经典示例 :) 谢谢!
      猜你喜欢
      • 1970-01-01
      • 2021-09-28
      • 2021-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多