# R 語言在繪圖上的應用-1 ## 輸入資料使用 `<-` 1.輸入資料的時候用`<-` 2.利用 `c()` 這個函數(c 意指是 combine)把多個數字賦值在一個物件中 3.數字要記得用 , 隔開 4.指令結束後就不要出現 , ``` weight <- c( 47, 55, 79, 63, 78, 64, 50, 53, 75, 54, 59, 58, 84, 70, 56, 71, 65, 59, 79, 81 ) ``` ## 繪圖用`hist()` ``` hist(weight) ``` ![](https://i.imgur.com/3ZvcDaP.png) ## 數列函式: `seq() ` 在統計運算中, 常需要產生數列向量,可以使用函式`seq()`產生 1.從 40 開始到 90 的且公差為 5 的數列 2.breakpts=40 45 50 ... 90 ``` breakpts <- seq(from=40, to=90, by=5 ) ``` ## 依題目要求做圖 1.`''`記得不要輸入錯誤,且輸入時一定要用英語 ``` hist(x=weight, #x軸代表的是weight breaks=breakpts, #設定寬度 right=FALSE, #用left-closed, right-open xlab='Weight (in kg)', #設定x軸名稱 main='Histogram of weights of 20 students' #設定圖的名字 ) ``` ![](https://i.imgur.com/rrK952G.png) ## 長條圖的繪製-用`barplot()` ``` datafreq <- c(3,2,0,5,4) barplot(height=datafreq) #圖的高度等於數字的最大值 barlabel <- c('A', 'B', 'C', 'D', 'E') barplot(height=datafreq, space=1/2, #bins 的間隔為 bins 的1/2 names.arg=barlabel, #names.arg:位於條低端的文字標籤 ylab="count", xlab="Alphabet letters", main="Give a title of your bar chart" ) ``` ![](https://i.imgur.com/Xr3EX5d.png) ## 將文字轉成時間 ### example 1 ``` datetimenow <- Sys.time() #datetimenow 為現在時間 datestr <- '2021-09-10' class(datestr) ``` 會得到 [1] "character" ``` mydate <- as.Date(datestr, format="%Y-%m-%d" ) ``` 1.時間資料的處理,假如不借助現有的“時間類別”資料型態的話,會頗麻煩,比如有兩個時間要比看看誰先誰晚,想知道兩個時間的間隔,或是要進一步要篩選一堆時間資料根據某個特定的時間點,所以使用內建處理時間的函數像是as.POSIXlt, as.POSIXlc, as.Date會方便很多。 2."年-月-日 時:分:秒" 在日期間以「-」區隔,時間以「:」區隔,兩者以一個空白分隔。 ``` class(mydate) ``` 經由上面轉換就會得到[1] "Date" ### 常用的時間 %Y - Year (4 digit, e.g., 2021) %y - year (2 digit, e.g., 21) %m - month (decimal number, e.g., 09) %B - Month (full name, e.g., September) %b - month (abbreviated, e.g., SEP) %H - Hours (24 hour, e.g., 22 for 10 PM) %M - Minute (from 00 to 59) ### example 2 ``` timester <- '10:40' maytime <-strptime(timester, format=“%H:%M” ) ``` `strptime()`得到的是時間型別資料,使用的是內部C語言函式轉換字串為時間 ## 折線圖 給定一組數字,代表是從3/4啓後30天田徑選手每天訓練的圈數,求折線圖 ``` laps <- c( 22,21,24,19,27,28,24,25,29,28, 26,31,28,27,22,39,20,10,26,24, 27,28,26,28,18,32,29,25,31,27) lapday <- seq(as.Date('2021-03-04'),by='days',length=30)#日期從3/4到4/3共30天 lapday <- as.Date(lapday, format='%Y-%m-%d') #把數字轉為日期 plot(x=lapday,y=laps, type='b', #type = "b"為點線圖 xaxt ='n', #使x軸消失 xlab = 'Month and Day', ylab = 'Number of laps' ) ``` ![](https://i.imgur.com/V89yLSC.png) #### 繪圖常用的fnction type = "l" 為折線圖 type = "p"為點點圖 type = "b"為點線圖 type = "s"像step function圖 #### 進階 在x軸上標記日期 ``` labs <- format(lapday, '%b-%d') #只需要取月份和天數 axis(side=1 ,at=lapday, labels=labs) ``` ![](https://i.imgur.com/Xt9Zjlr.png) 第一堂課結束