1.1 柱形图
setwd("e://Program Files//RStudio//temp") #设定工作目录
install.packages("RColorBrewer") #如果没有装
library(RColorBrewer) #载入包
citysales<-read.csv("citysales.csv") #读入数据
barplot(as.matrix(citysales[,2:4]), #转为矩阵
beside=TRUE, # 如果 TRUE,柱子排成并排的列
legend.text=citysales$City, #图例文本
args.legend=list(bty="n",horiz=TRUE), #图例参数:边框无;水平摆放
col=brewer.pal(5,"Set1"), #调用Set1画板中的5种颜色
border="white", #柱子边界白色
ylim=c(0,100), #y轴范围
ylab="Sales Revenue (1,000's of USD)", #y轴标签
main="Sales Figures") #主标题
box(bty="l") #指定整个坐标图形边界为“L”型
citysales<-read.csv("citysales.csv")
barplot(as.matrix(citysales[,2:4]),
legend.text=citysales$City,
args.legend=list(bty="n",horiz=TRUE),
col=brewer.pal(5,"Set1"),
border="white",
ylim=c(0,200), #注意范围要取充足,否则图形堆叠超过了坐标轴范围
ylab="Sales Revenue (1,000's of USD)",
main="Sales Figures")
这里的beside参数取的是默认值FALSE,画出来就是水平堆叠的效果。
1.3 用堆叠效果展示百分比
citysalesperc<-read.csv("citysalesperc.csv")
par(mar=c(5,4,4,8),xpd=T) #mar指定图形的边缘边距(下左上右);xpd if TRUE, all plotting is clipped to the figure region
barplot(as.matrix(citysalesperc[,2:4]),
col=brewer.pal(5,"Set1"),
border="white",
ylab="Sales Revenue (1,000's of USD)",
main="Percentage Sales Figures")
#数据中,每一个产品在5个城市的总百分比为100%,所以堆叠起来高度都是一样的
legend("right", #图例画在右方
legend=citysalesperc$City, #图例的文字信息
bty="n",
inset=c(-0.3,0), #图例距离图形的距离
fill=brewer.pal(5,"Set1")) #图例的填充颜色,与条形图中的一致
barplot(as.matrix(citysales[,2:4]),
beside=TRUE,
horiz=TRUE, #水平放置
legend.text=citysales$City,
args.legend=list(bty="n"),
col=brewer.pal(5,"Set1"),border="white",
xlim=c(0,100), xlab="Sales Revenue (1,000's of USD)",
main="Sales Figures")
#除了指定horiz=TRUE外,其他参数与其他情形一样
par(mar=c(5,4,4,8),xpd=T)
barplot(as.matrix(citysalesperc[,2:4]),
horiz=TRUE, #水平摆放
col=brewer.pal(5,"Set1"),
border="white",
xlab="Percentage of Sales",
main="Perecentage Sales Figu