LoginSignup
1
3

More than 5 years have passed since last update.

ggplot2における2軸プロットの使いみち

Last updated at Posted at 2017-01-22

ggplot2で2軸プロットをする - Qiita -でggplot2 2.2.0から2軸プロットが公式にサポートされている点について書いたが、意味の違う複数の系列を1枚のグラフに収めることについてHadleyが推奨するようになったとかそういうことではなくて(要するに先の記事の使い方はあまり良くない例です)、そもそもそういう用途に便利な実装になっていない。

主軸を何らかの関数で変換して第2軸を作成できるというのがポイントで、1つの系列に対して2つの軸が欲しいというときにこの仕組みが役に立つ。

例えばmpgはデータセットの名前の通り、燃費が「mile par gallon」で記録されているが、「km par little」の軸も欲しいという場合はこうする。

library(ggplot2)
library(dplyr)

# hwy : highway miles per gallon
#  1mile == 1.60934km
#  1gallon == 3.78541L
#  ∴ mile / gallon = 1.60934 / 3.78541 km / L

mpg2kpl <- function(x) x * 1.60934 / 3.78541

mpg %>% 
  ggplot(aes(displ, hwy)) +
  geom_point() +
  scale_y_continuous(sec.axis = sec_axis(~ mpg2kpl(.), name = "km/L")) +
  labs(y = "mile/gal") +
  theme_classic()

Rplot01.png

第2x軸を使う例。

# temperature: deg C
# pressure:    mm of Hg
# 1 mmHg == 0.133322 kPa

mmHg2kPa <- function(x) x * .133322
C2K <- function(x) x + 273.15

pressure %>%
  ggplot(aes(temperature, pressure)) +
  geom_point() +
  scale_x_continuous(sec.axis = sec_axis(~ C2K(.), name = "Temperature (K)")) +
  scale_y_continuous(sec.axis = sec_axis(~ mmHg2kPa(.), name = "Pressure (kPa)")) +
  labs(x = "Temperature (C)",  y = "Pressure (mm of Hg)") +
  theme_classic()

Rplot02.png

参考

ggplot2 2.2.0 coming soon! | RStudio Blog

1
3
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
1
3