问题提得很清楚,赞。这种有违数学上常见的坐标轴一直也困扰着我(不过R的作者应该也有自己的考量)~
也许没有简单直接的解决方案,我的解决方法是一开始限制R自动给出坐标轴,稍后自己用lines加arrows手动画上坐标轴。
见下面的例子:
- par(mar = c(1, 1, 0, 0) + 0.1)
- x <- c(0, 1, 2, 3)
- p <- c(1/8, 3/8, 3/8, 1/8)
- plot(x, p, type = "n", axes = F, xlab = "", ylab = "",
- xlim = c(-0.2, 3.2), ylim = c(-0.1, 1.2))
- arrows(x0 = -0.2, y0 = 0, x1 = 3.2, y1 = 0, length = 0.1, angle = 15)
- arrows(x0 = 0, y0 = 0, x1 = 0, y1 = 1.2, length = 0.1, angle = 15)
- lines(c(x[1], x[1]), c(0, p[1]), col = "blue", lwd = 3)
- lines(c(x[2], x[2]), c(0, p[2]), col = "blue", lwd = 3)
- lines(c(x[3], x[3]), c(0, p[3]), col = "blue", lwd = 3)
- lines(c(x[4], x[4]), c(0, p[4]), col = "blue", lwd = 3)
- text(x = 3.2, y = -0.03, labels = expression("x"))
- text(x = 0, y = -0.02, labels = 0)
- text(x = 1, y = -0.02, labels = 1)
- text(x = 2, y = -0.02, labels = 2)
- text(x = 3, y = -0.02, labels = 3)
- text(x = -0.1, y = 1.2, labels = expression("F(x)"))
- text(x = -0.1, y = 1/8, labels = expression(frac(1, 8)))
- text(x = -0.1, y = 3/8, labels = expression(frac(3, 8)))
- text(x = -0.1, y = 4/8, labels = expression(frac(4, 8)))
- text(x = -0.1, y = 7/8, labels = expression(frac(7, 8)))
- text(x = -0.1, y = 1, labels = expression(1))
- # Add tickmarks on x-axis and y-axis
- xcor <- c(0, 1, 2, 3)
- ycor <- c(1/8, 3/8, 4/8, 7/8, 1)
- for (xv in xcor) {
- lines(c(xv, xv), c(0, 0.05), col = "black")
- }
- for (yv in ycor) {
- lines(c(0, 0.05), c(yv, yv), col = "black")
- }
- # Start drawing cdf
- lines(c(-0.2, 0), c(0, 0), col = "orange", lwd = 3)
- lines(c(0, 1), c(1/8, 1/8), col = "orange", lwd = 3)
- lines(c(1, 2), c(4/8, 4/8), col = "orange", lwd = 3)
- lines(c(2, 3), c(7/8, 7/8), col = "orange", lwd = 3)
- lines(c(3, 3.2), c(1, 1), col = "orange", lwd = 3)
- points(c(0, 1, 2, 3), c(1/8, 4/8, 7/8, 1), pch = 19, col = "orange", cex = 1.5)
- points(c(0, 1, 2, 3), c(0, 1/8, 4/8, 7/8), pch = 1, col = "orange", cex = 1.5)
- points(c(0, 1, 2, 3), c(1/8, 3/8, 3/8, 1/8), pch = 4, col = "blue", cex = 1.5)
- legend(x = 0.5, y = 1, c(expression(paste("pmf of ", X)), expression(paste("cdf of ", X))),
- lwd = c(3, 3), col = c("blue", "orange"))
复制代码
这段代码给出的图片输出如下:
代码可能会有点烦,不知道这个问题在最近流行的ggplot2, ggvis包里有没有得到更好的处理。权作抛砖引玉吧。
|