服务热线
178 0020 3020
本次内容中多了一个堆积的柱形图,同时数据从excel里面的导入,在数据转换上曾遇到一点小麻烦,注意看代码中的注释。
首先Excel内容如下:

| 1月 | 2月 | 3月 | 4月 | 5月 | 6月 | |
| 一部 | 2 | 4 | 1 | 6 | 5 | 2 |
| 二部 | 2 | 5 | 2 | 7 | 6 | 2 |
| 三部 | 3 | 3 | 1 | 7 | 5 | 6 |
| 总营业额 | 7 | 12 | 5 | 20 | 16 | 10 |
代码如下:
library("xlsx")
data <- read.xlsx("E:/R3.xlsx",sheetIndex = 1,encoding="UTF-8")
#print(data[2:4,2:7])
#as.vector将因子转变为向量
department <- as.vector(data[1:3,1])
#获得中间的三组数据
p1 <- data[1:3,2:7]
#as.matrix将frame转为矩阵
content <- as.matrix(p1)
xlegend <- c("1月","2月","3月","4月","5月","6月")
color <- c('red','green','blue')
png(file="E:/R3.png")
barplot(
content,
names.arg = xlegend,
xlab = "月份",
ylab = "收益",
col=color
)
#添加标签
legend(
"topleft",
department,
fill = color
)
dev.off()得出图片如下:

从Excel里面读取数据使用read.xlsx函数,读取得到的结果为一个data.frame数据帧; 在barplot函数里面提供的数据必须为向量或者矩阵,因此用到了as.vector()和as.matrix()函数。这相当于其他编程语言中的类型转换函数
附件