这篇简直是白写了,写到后面发现ggplot明显更好用
3.1 使用图形
attach(mtcars)
plot(wt, mpg) #x轴wt,y轴pg
abline(lm(mpg ~ wt)) #画线拟合
title("Regression of MPG on Weight")
detach(mtcars)
R语言中画图只有一幅,如果要画多幅,用dev.new()
3.2 例子
dose <- c(20, 30, 40, 45, 60)
drugA <- c(16, 20, 27, 40, 60)
drugB <- c(15, 18, 25, 31, 40)
plot(dose, drugA, type = "b") #type="b"是点线图
3.3 图形参数
par():修改图形参数
3.3.1 符号和线条
pch:指定绘制点时使用的符号
cex:指定符号大小,默认为1,1.5表示放大为默认值的1.5倍
lty:指定线条类型,linetype,真难记啊直接写完整英文单词不好吗
lwd:指定线条宽度,linewidth
3.3.2 颜色
col:绘图颜色,col=c("red","blue"),
col.axis:坐标轴刻度文字的颜色
col.lab:坐标轴标签的颜色
col.main:标题颜色
col.sub:副标题颜色
fg:图形前景色
bg:图形背景色
colors():返回所有颜色名称
返回连续形颜色,rainbow(),heat.colors(),terrain.colors(),topo.colors(),cm.colors(),gray()
n <- 10
mycolors <- rainbow(n)
pie(rep(1, n), labels = mycolors, col = mycolors)
mygrays <- gray(0:n/n)
pie(rep(1, n), labels = mygrays, col = mygrays)
3.3.3 文本属性
cex:文本大小
cex.axis:坐标轴刻度文字的缩放倍数
cex.lab:坐标轴名称的缩放倍数
cex.main:标题的缩放倍数
cex.sub:副标题的缩放倍数
font:字体,1常规,2粗体,3斜体,4粗斜体,5=符号字体
font.axis
font.lab
font.main
font.sub
ps:字体磅值
3.3.4 图形尺寸与边界尺寸
pin:以英寸表示图形尺寸
mai:以数值向量表示的边界大小,顺序为下左上右,单位是英寸
mar:以数值向量表示的边界大小,单位是英分
3.4 添加文本,自定义坐标轴和图例
main:标题
sub:副标题
xlab/ylab:X与Y轴名称
xlim/ylim:X与Y轴范围
如下图
plot(dose, drugA, type = "b", col = "red", lty = 2, pch = 2, lwd = 2, main = "Clinical Trials for Drug A", sub = "This is hypothetical data", xlab = "Dosage", ylab = "Drug Response",
xlim = c(0, 60), ylim = c(0, 70))
3.4.1 标题
title():
title(main="main text",sub="sub title",xlab="x axis label",ylab="y axis label")
3.4.2 坐标轴
axis()
如下代码
x <- c(1:10)
y <- x
z <- 10/x
opar <- par(no.readonly = TRUE)
par(mar = c(5, 4, 4, 8) + 0.1)
plot(x, y, type = "b", pch = 21, col = "red", yaxt = "n", lty = 3, ann = FALSE)
lines(x, z, type = "b", pch = 22, col = "blue", lty = 2)
axis(2, at = x, labels = x, col.axis = "red", las = 2)
axis(4, at = z, labels = round(z, digits = 2), col.axis = "blue", las = 2, cex.axis = 0.7, tck = -0.01)
mtext("y=1/x", side = 4, line = 3, cex.lab = 1, las = 2, col = "blue")#在图形边界添加文本
title("An Example of Creative Axes", xlab = "X values", ylab = "Y=X")
par(opar)
3.4.3 参考线
abline(h=yvalues,v=xvalues)
3.4.4 图例
lengend()
如下代码
dose <- c(20, 30, 40, 45, 60)
drugA <- c(16, 20, 27, 40, 60)
drugB <- c(15, 18, 25, 31, 40)
opar <- par(no.readonly = TRUE)
par(lwd = 2, cex = 1.5, font.lab = 2)
plot(dose, drugA, type = "b", pch = 15, lty = 1, col = "red",
ylim = c(0, 60), main = "Drug A vs. Drug B", xlab = "Drug Dosage",
ylab = "Drug Response")
lines(dose, drugB, type = "b", pch = 17, lty = 2, col = "blue")
abline(h = c(30), lwd = 1.5, lty = 2, col = "grey")
library(Hmisc)
minor.tick(nx = 3, ny = 3, tick.ratio = 0.5)
legend("topleft", inset = 0.05, title = "Drug Type",
c("A", "B"), lty = c(1, 2), pch = c(15, 17), col = c("red",
"blue"))
par(opar)
3.4.5 文本标注
text():在绘图区域内添加文本
mtext():在四个边界添加文本
3.5 图形的组合
par(mfrow=c(2,2)) #一个图中放4个小图,2行2列
layout(matrix(c(1, 1, 2, 3), 2, 2, byrow = TRUE)) #一个图中放了3个小图,第一行1个,第二行2个