2013-09-22 73 views
0

我是一位新的R用戶,無法在條形圖中繪製一些數據。對不起,如果這很容易做到,我只是無法弄清楚。 我有六組數據:1號,5號和10號汽車#1的3組數據,以及1,5號和10號汽車#3的3組數據,其中每輛汽車在每個年齡的測量結果包括1.)統計汽車外部的凹痕總數,以及2.)除去油漆的凹痕數量。我想製作一個帶有6個酒吧的箱子圖,對應於每輛汽車和他們各自的年齡,其中列高度是去除油漆的凹痕總數,標準偏差線條。 這是我一直在努力,到目前爲止(僅包括2數據集):具有標準差的R barplot

car1yr1 = c(rep(0, 101), rep(1, 9)) #car has 9 dents that remove paint 

car1yr5 = c(rep(0, 131), rep(1, 19)) #car has 19 dents that remove paint 

sd1 = sd(car1yr1) 

sd2 = sd(car1yr5) 

stdv = c(sd1, sd2) 

car1yr1 = car1yr1[1:150] 

dentsCar1 = data.frame("Car1Yr1" = car1yr1, "Car1Yr5" = car1yr5) 

barplot(as.matrix(dentsCar1, ylim = c(0, 50), beside = TRUE)) 

我發現的誤差線爲例:arrows(bar, x, bar, x+ -(stdv), length = 0.15, angle = 90),但我不能讓這與我的號碼的工作。另外,在這個例子中,y軸停在15,但是條形Car1Yr5一直到19。我怎樣才能畫一個y軸到20或30? 同樣,我是R新手,任何幫助將不勝感激。我一直試圖解決這個問題,我自己解決了大約2周。謝謝。

+0

我有點困惑 - 你想計算一輛車的計數標準偏差?您不應該繪製每輛車的每個油漆清除凹痕的數量,並且該車的所有凹痕的標準偏差。 – dayne

回答

0

我對你的數據有點困惑......我從你的例子中可以看出,汽車1有101個凹痕,沒有去除油漆,9個沒有,而汽車2有131個沒有,19個沒有。

現在計算凹痕數量的標準偏差對我來說沒有多大意義......您正在繪製計數數據,所以您不應該有任何標準偏差,除非您擁有相同型號的多輛車你想看到汽車之間的變化。

做的是計算凹痕做去除油漆%的最好的事情:

car1yr1 = c(rep(0, 101), rep(1, 9)) #car has 9 dents that remove paint 
car1yr5 = c(rep(0, 131), rep(1, 19)) #car has 19 dents that remove paint 

# The total number of observations is the total number of dents 
total.dents.1 <- length(car1yr1) 
total.dents.5 <- length(car1yr5) 
# The dents that remove paint are marked as 1, the others with 0, 
# so we can just sum all of the data to get the number of paint-removing dents 
dents.paint.1 <- sum(car1yr1) 
dents.paint.5 <- sum(car1yr5) 
# Alternatively you can use 
# dents.paint.1 <- length(which(car1yr1==1)) 
# Calculate the % 
dents.paint.perc.1 <- dents.paint.1/total.dents.1 
dents.paint.perc.5 <- dents.paint.1/total.dents.5 

df <- data.frame(dents.paint.perc.1, dents.paint.perc.5) 

# Plot the data. 
# ylim specifies the limits of the y axis 
# ylab defines the axis title. 
# las=1 puts the labels on the y axis horizontally 
# names defines the labels on the x axis 
barplot(as.matrix(df)*100, ylim=c(0,20), 
     ylab="% dents removing paint", las=1, 
     names=c("Car 1 year 1", "Car 1 year 5")) 

一般來說它會好得多把所有的數據在一個列表中,以便您可以使用*apply函數族對所有數據集執行重複操作。這會給你更清潔和更易於管理的代碼。另外,如果添加更多數據,它會自動將它添加到圖中。