绘制坐标
有时候我们绘制坐标的时候,需要改变坐标轴的定义,我们以日期为横坐标绘制时间序列为例讲解
先列举简单的例子:
rnorm(n, mean = 0, sd = 1)
n 为产生随机值个数(长度),mean 是平均数, sd 是标准差 。
> rnorm(10,1,sd = 2)
[1] 1.98984356 -1.93403191 -1.15324772 0.84623524 -0.73123833 -2.77682328 -0.74316683 -0.02913632 -0.80063421 3.23976243
用随机数绘制曲线:
require(stats) # for rnorm
plot(x=1:10, y=rnorm(10,1,sd = 2), type = 'l')
what type of plot should be drawn. Possible types are
"p" for points,
"l" for lines,
"b" for both,
"c" for the lines part alone of "b",
"o" for both ‘overplotted’,
"h" for ‘histogram’ like (or ‘high-density’) vertical lines,
"s" for stair steps,
"S" for other steps, see ‘Details’ below,
把上述内容绘制成时间序列
> plot(x=1:10, y=rnorm(10,1,sd = 2), type = 'l',xaxt='n') # 原坐标X 不绘制,否则会重叠
> axis(side = 1, at = c(2,4,6,8,10), labels = c("2016-05-24", "2016-05-26", "2016-05-30", "2016-06-01", "2016-06-03"))
自动保存成图片文件
png(filename = "Rplot%03d.png",
width = 480, height = 480, units = "px", pointsize = 12,
bg = "white", res = NA, family = "", restoreConsole = TRUE,
type = c("windows", "cairo", "cairo-png"), antialias)
在 plot 的上方和下方加入 png function 和 devoff():
require(stats) # for rnorm
png(file='draw.png', bg="white", width = 300, height = 200)
plot(x=1:10, y=rnorm(10,1,sd = 2), type = 'l',xaxt='n', main = 'draw') # 增加坐标的 名称 draw
axis(side = 1, at = c(2,4,6,8,10), labels = c("2016-05-24", "2016-05-26", "2016-05-30", "2016-06-01", "2016-06-03"))
dev.off()
创建 png 的时候 可以指定分辨率, 可以看出这个图片比之前的小一些