LoginSignup
12
15

More than 5 years have passed since last update.

ggplot2で縦軸と横軸をひっくり返したい

Last updated at Posted at 2015-08-01

(2016/03/15追記)ggplot2 v2.1.0で動作確認しました。

Q

例えば以下のようなグラフで、x軸とy軸をひっくり返したい(横棒グラフ)にしたいのですが、どうしたらいいのでしょうか?

NG_example.R
library(ggplot2)
ggplot(mtcars, aes(x = as.factor(gear))) +
  geom_bar()

NG_example.R-1.png

A

+ coord_flip()を追加すると、x軸とy軸が入れ替わります:

OK_example.R
ggplot(mtcars, aes(x = as.factor(gear))) +
  geom_bar() +
  coord_flip()

OK_example.R-1.png

この設定は、別に棒グラフだけではなく、全てに適用可能です。

応用

このcoord_flip()を設定した場合、更に軸に設定を加えるときは元の座標軸に設定してください:

例) count軸の範囲を変更する場合:

OK_example2.R
ggplot(mtcars, aes(x = as.factor(gear))) +
  geom_bar() +
  coord_flip() +
  ylim(c(0,20))

OK_eample2.R-1.png

また、棒グラフを横にすると、下から順番にならびます。軸の内容の並べ替えについては、以下の記事を参照してください:
- ggplot2逆引き - x軸を並べ替えたい - Qiita

今回x軸はfactor型なので、順番を入れ替えるには以下のようにreorder()を当てて変更しておく必要があります:

例) as.factor(gear)軸の順序を反転する場合:

OK_example3.R
ggplot(mtcars, aes(x = reorder(as.factor(gear), gear * -1))) +
  geom_bar() +
  coord_flip()

OK_example3.R-1.png

なお、x軸が連続変量であったならば、単に+ scale_x_reverse()を追加すればOKです。

例) gear軸の順序を反転する場合:

OK_example4.R
ggplot(mtcars, aes(x = gear)) +
  geom_bar() +
  coord_flip() +
  scale_x_reverse()

OK_example4.R-1.png

参考

12
15
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
12
15