2016-06-20 39 views
0

R是新手,试图找出barplot。
我正在尝试在R中创建一个barplot,显示由第三列分组的2列中的数据。在R中有多个栏的Barplot

数据框名称:SprintTotalHours

柱的数据:

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

我想barplot显示旁边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) 

我想用基地图形,但如果它不能做那么我并不反对必要时安装一个软件包。

Sweet Paint Skills

回答

4

plot

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); 
+1

很厚道的先生黄金街。我会在3小时内投票 – rawr

+1

哈,我喜欢这个。 – alistaire

+0

我采取了这个答案和digEmAll的混合来获得我想要的外观。这最终是我的选择,因为它看起来就像我的蹩脚的油漆图,所以要求满足!但是,我使用digEmAll的代码使它看起来更像他的经典示例,不知道我想要什么:)谢谢! – JRDew

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')) 

enter image description here

+1

伟大的答案,按预期工作和爱的音符。我使用了这个答案和bgoldst的组合来获得我想要的外观。最终选择bgoldst是因为他匹配了我的油漆示例的外观和感觉。不过,我更喜欢这一款的外观,所以我从这里拿了一些代码。谢谢! – JRDew

+0

很高兴能有所帮助:) – digEmAll

2

你需要融到长期形成这样你就可以组。虽然你可以这样做在基地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') 

ggplot

使用基础R,如果你喜欢,但这种方法(或多或少)是传统的方法在这一点上。