LoginSignup
17
23

More than 5 years have passed since last update.

ggplot2で同一グラフに2変数の折れ線グラフを描きたい

Last updated at Posted at 2015-09-08

2016/04/12追記: ggplot2 v2.1.0にて動作を確認しました

Q

このようなデータが手元にあります:

test_data <- data.frame(
var0 = 100 + c(0, cumsum(runif(49, -20, 20))),
var1 = 150 + c(0, cumsum(runif(49, -10, 10))),
date = seq.Date(as.Date("2002-01-01"), by="1 month", length.out=100))

この時系列変数var0var1の両方共を、dateをx軸にしてggplot2でどうやったら描けますか? できればvar0var1の色を変えて、さらに凡例も付けれたら嬉しいです。

A

もし変数が少ないのであれば、マニュアルで別々に作成ビルドアップできますよ:

library(ggplot2)
ggplot(test_data, aes(date)) +
  geom_line(aes(y = var0, colour = "var0")) +
  geom_line(aes(y = var1, colour = "var1"))

OK_example1.R-1.png

一般的なアプローチとしては、tidyrパッケージを利用してデータを縦型(long format)に変換していく方法があります:

library(tidyr)
library(ggplot2)

test_data_long <- tidyr::gather(test_data, key="variable", value = value, -date) # 縦型に変換

head(test_data_long, 6)

ggplot(data=test_data_long, aes(x=date, y=value, colour=variable)) +
  geom_line()
date variable value
2002-01-01 var0 100.00000
2002-02-01 var0 95.11673
2002-03-01 var0 80.26050
2002-04-01 var0 67.80293
2002-05-01 var0 49.52975
2002-06-01 var0 43.69161

OK_example2a.R-1.png

データを縦型のデータに変換し、var0var1を分けるための変数で色分けを指定すればこのようになります。

参考

この記事は、StackOverflowに投稿された以下の記事をベースに、コードを一部改変して翻訳して作成しました:
- r - Plotting two variables as lines using ggplot2 on the same graph - Stack Overflow

関連ドキュメント:
- geom_line. ggplot2 0.9.3.1

17
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
23