Windows下R畫圖舉例
例1:
從city.xlsx中讀取數據,並畫出折線圖。
excel數據如圖1
a b
圖1
代碼如下:
#打開庫文件
library("xlsx")
#讀取excel數據
data1=read.xlsx("city.xlsx",sheetIndex = 1)
data2=read.xlsx("city.xlsx",sheetIndex = 2)
data3=read.xlsx("city.xlsx",sheetIndex = 3)
data4=read.xlsx("city.xlsx",sheetIndex = 4)
#給圖片命名
png(file="city.jpg")
#繪制第一幅圖
plot(data1$runningtime~data1$length,type="o",pch=1,ylim=c(0,5),main="test",xlab="length",ylab="running time",col="blue")
#分別添加圖
lines(data2$runningtime~data2$length,type="o",pch=2,col="red")
lines(data3$runningtime~data3$length,type="o",pch=4,col="green")
lines(data4$runningtime~data4$length,type="o",pch=16,col="black")
#制作圖例
legend("topright",c("first","second","third","forth"),bty=‘n‘,pch=c(1,2,4,16),lty=1,col=c(‘blue‘,‘red‘,‘green‘,‘black‘))
#保存
dev.off()
結果:
例2:
從city1.xlsx中讀取數據,並畫出條形圖。
excel數據如圖2
圖2
代碼:
#打開庫文件
library("xlsx")
#讀取excel數據
data1=read.xlsx("city1.xlsx",sheetIndex = 3)
data=data1[,2:5]
M = as.matrix(data1[,2:5])
png(file="city1.jpg")
#畫圖
barplot(M,col=rainbow(4),ylim=c(0,100),beside=TRUE,legend.text=data1$name,args.legend=list(bty="n",horiz=TRUE))
dev.off()
結果:
Windows下R畫圖舉例