本篇介绍R语言base系统绘制散点图、条形图、直方图、箱线图、饼图,还将简单介绍点图、核密度图、折线图。
散点图:
attach(mtcars)
plot(wt, mpg,
main="Basic Scatterplot of MPG vs. Weight",
xlab="Car Weight (lbs/1000)",
ylab="Miles Per Gallon ", pch=19)
abline(lm(mpg ~ wt), col="red", lwd=2, lty=1)
lines(lowess(wt, mpg), col="blue", lwd=2, lty=2)
条形图
library(vcd)
counts <- table(Arthritis$Improved, Arthritis$Treatment)
counts
par(mfrow=c(1,2))
# stacked barplot
barplot(counts,
main="Stacked Bar Plot",
xlab="Treatment", ylab="Frequency",
col=c("red", "yellow","green"),
legend=rownames(counts))
# grouped barplot
barplot(counts,
main="Grouped Bar Plot",
xlab="Treatment", ylab="Frequency",
col=c("red", "yellow", "green"),
legend=rownames(counts), beside=TRUE)
par(mfrow=c(1,1))
直方图
箱线图
创建一个箱线图在 R 中的基本的语法是:
boxplot(x,data,notch,varwidth,names,main)
以下是所使用的参数的说明:
x - 是一个向量或一个公式
data - 是数据帧
notch - 是一个逻辑值。设置为TRUE画一个缺口
varwidth - 是一个逻辑值。设置为 true 时来画的宽度成正比到样本大小的方块。
names - 是将每个箱线图下被打印的组标签。
main - 用于给出曲线图的标题。
下面的脚本将创建 mpg(英里每加仑)和cyl(气缸数)之间的关系的一个箱线图
boxplot(mpg~cyl,data=mtcars,
main="Car Milage Data",
xlab="Number of Cylinders",
ylab="Miles Per Gallon")
饼图
点图
x <- mtcars[order(mtcars$mpg),]
x$cyl <- factor(x$cyl)
x$color[x$cyl==4] <- "red"
x$color[x$cyl==6] <- "blue"
x$color[x$cyl==8] <- "darkgreen"
dotchart(x$mpg,
labels = row.names(x),
cex=.7,
pch=19,
groups = x$cyl,
gcolor = "black",
color = x$color,
main = "Gas Mileage for Car Models\ngrouped by cylinder",
xlab = "Miles Per Gallon")
核密度图
折线图
opar <- par(no.readonly=TRUE)
par(mfrow=c(1,2))
t1 <- subset(Orange, Tree==1)
plot(t1$age, t1$circumference,
xlab="Age (days)",
ylab="Circumference (mm)",
main="Orange Tree 1 Growth")
plot(t1$age, t1$circumference,
xlab="Age (days)",
ylab="Circumference (mm)",
main="Orange Tree 1 Growth",
type="b")
par(opar)