今週も特にありません

進捗どうですか?

ggplot2で値の正負によって、色分けする

データの値の正負によって色分けをしたい場合があります。この場合、mutateでTRUE/FALSEの判定をした新しいカラムを追加して可視化するということをよくしていましたが、データが大変多い場合などには、可視化の色分けのためだけにカラムを追加するということはあまりしたくありません。

ggplotの中でなんとかできないか調べていたら、aesの中で比較演算子を使って簡単に色分けができる。ということを今さら知ったので、メモします。

library(tidyverse)

sample_tbl <- tibble(
  type = LETTERS,
  value = runif(length(LETTERS), -1, 1)
)

sample_tbl %>%
  ggplot(aes(x = type, y = value, fill = value > 0)) +
  geom_bar(stat = "identity") + 
  labs(x = "", y = "") + theme_bw() +
  theme(axis.text = element_text(size = 20),
        legend.position = "none")

value > 0を指定するだけでした...

f:id:masaqol:20190113161947p:plain

加えて、こちらはよく調べられていると思われる昇順、降順で並べ替えてのプロットですが、reorderを使ってすぐにできます。

sample_tbl %>%
  ggplot(aes(x = reorder(type, value), y = value, fill = value > 0)) +
  geom_bar(stat = "identity") + 
  labs(x = "", y = "") + theme_bw() +
  theme(axis.text = element_text(size = 20),
        legend.position = "none")

f:id:masaqol:20190113162143p:plain