JRD*_*Dew 3 charts r bar-chart
R 新手并试图找出条形图。
我正在尝试在 R 中创建一个条形图,它显示来自按第三列分组的 2 列的数据。
数据框名称: SprintTotalHours
包含数据的列:
OriginalEstimate,TimeSpent,Sprint
178,471.5,16.6.1
210,226,16.6.2
240,195,16.6.3
Run Code Online (Sandbox Code Playgroud)
我想要一个条形图,显示每个冲刺的OriginalEstimate旁边TimeSpent。我试过这个,但我没有得到我想要的:
colours = c("red","blue")
barplot(as.matrix(SprintTotalHours),main='Hours By Sprint',ylab='Hours', xlab='Sprint' ,beside = TRUE, col=colours)
abline(h=200)
Run Code Online (Sandbox Code Playgroud)
我想使用基本图形,但如果无法完成,那么我不反对在必要时安装软件包。

使用基础 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'))
Run Code Online (Sandbox Code Playgroud)
你需要融化成长形式,这样你才能分组。虽然您可以在基础 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')
Run Code Online (Sandbox Code Playgroud)
如果您愿意,可以使用基本 R,但这种方法(或多或少)是目前的常规方法。
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();
Run Code Online (Sandbox Code Playgroud)
数据
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);
Run Code Online (Sandbox Code Playgroud)