例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()
结果: