###5.繪圖工具#### #5.1 基本繪圖函數plot()#### View(cars) help(cars) #行駛速度與剎車距離 head(cars) plot(cars) plot(cars$dist~cars$speed) #指定y軸表示剎車距離 plot(cars$speed~cars$dist) #指定x軸表示剎車距離 #5.2 為了方便將兩幅圖畫在一起進行對比 #### windows() #用單獨的窗口顯示圖形以獲得更好的顯示效果,注意windows命令在前 par(mfrow=c(2,2)) #c(2,2)表示生成一個2*2的矩陣 plot(cars$dist~cars$speed) plot(cars$speed~cars$dist) #5.3 函數的參數####(注意代碼的美觀) plot(cars$dist~cars$speed, # y~x main="剎車距離與車速之間的關系", # 畫標題 xlab="Speed (miles per hour)", #X坐標軸標題 ylab="Distance travelled (miles)", #Y坐標軸標題 xlim=c(0,30), #設置X軸范圍為從0到30 ylim=c(0,140), #設置Y軸范圍為從0到140 xaxs="i", #設置X軸風格internal yaxs="i", #設置Y軸風格internal col="red", #設置“散點”的顏色為紅色 pch=19) #設置散點的形狀為實心圓點 #5.4繪制線圖#### #使用微信公眾號用戶數據 setwd("~") num<-read.csv(file = "wechat.csv") head(num) windows() plot(num$NetGrowth~as.Date(num$date), type="l", mian="每日凈增長變化", xlab="日期", ylab ="凈增長人數",col="red" ) #5.5 低水平繪圖函數lines()#### lines(num$NetGrowth~as.Date(num$date),col="red") example("lines") plot(cars, main = "Stopping Distance versus Speed") lines(stats::lowess(cars)) #此段代碼為散點圖加上光滑的曲線 #5.6 柱形圖#### #使用數據集BOD View(BOD) #使用基礎繪圖包 barplot(BOD$demand,names.arg = BOD$Time) #先輸出頻數表,然后在用條形圖繪制 table(mtcars$cyl) barplot(table(mtcars$cyl)) #改變圖形的方向 windows() par(mfrow=c(1,2)) barplot(BOD$demand,names.arg = BOD$Time) barplot(BOD$demand,names.arg = BOD$Time,horiz = TRUE) ###5.7.繪制直方圖#### windows() par(mfrow=c(1,2)) hist(mtcars$mpg) hist(mtcars$mpg,breaks=10) #控制分區數目 ###5.8繪制箱線圖#### #使用數據集ToothGrowth View(ToothGrowth) #使用plot函數時,當x軸為分類變量,y軸為數值型變量時,默認輸出箱線圖 plot(ToothGrowth$supp,ToothGrowth$len) ###5.9 繪圖設備(輸出圖形的格式)#### ?device #查看可以使用的圖形設備 setwd("~") pdf("boxplot.pdf") #在圖形設備中輸出圖形名稱 plot(ToothGrowth$supp,ToothGrowth$len) dev.off() #關閉當前圖形設備,相當於保存該圖形 png("boxplot.png") plot(ToothGrowth$supp,ToothGrowth$len) dev.off() pdf("綜合圖.pdf") #在你希望將所有圖形輸出到一個文件中時,這樣做,不支持PNG格式 hist(mtcars$mpg) hist(mtcars$mpg,breaks=10) plot(ToothGrowth$supp,ToothGrowth$len) dev.off() #圖形設備設置 dev.cur() #查看當前正在使用的圖形設備 dev.set(3) #把當前正在使用的圖形設別設置為其它設備 #5.10 其他常用圖形#### example("pie") #查看餅圖的使用方法和示例 example("plot.ts")#時間序列圖示例 #5.11 繪圖參數#### setwd("~") wec<-read.csv(file = "wechat.csv",header = TRUE) head(wec) windows() plot.ts(wec$NetGrowth,col="red") points(wec$NetGrowth,bg="skyblue",color="red",pch=21) abline(h=mean(wec$NetGrowth),col="blue") title("公眾號日凈增關注人數變化") box() #5.12 生成時間序列的函數#### ts(1:10, frequency = 4, start = c(1958, 1)) #生成時間序列,季度,起始 print( ts(1:10, frequency = 7, start = c(12, 2)), calendar = TRUE) #星期 日歷 gnp <- ts(cumsum(1 + round(rnorm(100), 2)), start = c(1954, 7), frequency = 12) z <- ts(matrix(rnorm(300), 100, 3), start = c(1961, 1), frequency = 12) class(z);head(z);plot(z)