Rできれいな図を描く(折れ線グラフ)



2008

2009

2010

2011

2012

2013

2014

2015

A

43.30

44.50

43.60

44.30

44.20

43.80

43.50

43.70

B

22.80

21.90

21.00

20.20

19.40

18.80

17.80

16.90

C

10.60

10.70

11.70

11.80

12.30

13.10

14.20

14.20

データの読み込み(Excelからクリップボード経由で読み込む想定)

mydata <- read.table(file = "clipboard", header = T, row.names = 1, check.names = F)

作図する

x.axis <- names(mydata)

myplot <- function(x, ...) plot(x,
                   pch = 19,
                   ylim = c(0, 70),
                   type = "o",
                   ann = F,
                   yaxs = "i",
                   lwd = 4,
                   cex.axis = 1.5,
                   las = 1,
                   ...)

myplot(x.axis, mydata[1,], col = rgb(145, 90, 35, maxColorValue = 255))
par(new = T)
myplot(x.axis, mydata[2,], axes = F, col = rgb(0, 150, 215, maxColorValue = 255))
par(new = T)
myplot(x.axis, mydata[3,], axes = F, col = rgb(255, 0, 0, maxColorValue = 255))
abline(h = seq(0, 70, 10), lty = "dashed")

yaxs = "i":x軸の交点をy=0にする
las = 1:軸ラベルを水平に描く
f:id:touch-sp:20171211193107p:plain:w500

便利な利用方法

  • メタファイルとしてコピー
  • PowerPointに貼り付け
  • グループ化解除

おまけ(プロットエリアのみ塗りつぶす)

x.axis <- names(mydata)

myplot <- function(x, ...) plot(x,
                   pch = 19,
                   xlim = c(2007.8, 2015.2),
                   ylim = c(0, 70),
                   ann = F,
                   xaxs = "i",
                   yaxs = "i",
                   lwd = 4,
                   cex.axis = 1.5,
                   las = 1,
                   ...)

myplot(x.axis, mydata[1,], type = "n")
rect(2007.8, 0, 2015.2, 70, col = rgb(255, 245, 235, maxColorValue = 255))
abline(h = seq(0, 70, 10), lty = "dashed")

par(new = T)
myplot(x.axis, mydata[1,], axes = F, col = rgb(145, 90, 35, maxColorValue = 255), type = "o")

par(new = T)
myplot(x.axis, mydata[2,], axes = F, col = rgb(0, 150, 215, maxColorValue = 255), type = "o")

par(new = T)
myplot(x.axis, mydata[3,], axes = F, col = rgb(255, 0, 0, maxColorValue = 255), type = "o")

f:id:touch-sp:20171211223712p:plain:w500

補足

以下でも同じグラフが描ける

x.axis <- as.numeric(names(mydata))

x.max <- max(x.axis) + 0.2
x.min <- min(x.axis) - 0.2

mycol = c(rgb(145, 90, 35, maxColorValue = 255),
          rgb(0, 150, 215, maxColorValue = 255),
          rgb(255, 0, 0, maxColorValue = 255))


plot(0, 0, type = "n", xlim = c(x.min, x.max), ylim = c(0, 70),
     xlab = "", ylab = "",
     xaxs = "i", yaxs = "i",
     las = 1,
     cex.axis = 1.5)

rect(x.min, 0, x.max, 70, col = rgb(255, 245, 235, maxColorValue = 255))
abline(h = seq(0, 70, 10), lty = "dashed")

for (i in 1:length(x.axis)) {
    points(x.axis, mydata[i,], pch = 19, col = mycol[i], lwd = 4, type = "o", cex = 1.5)
    }

cex = 1.5:プロットを大きくしている