R言語による医療データ分析

R言語によるデータ分析のオンラインコースを中心に、さまざまなデータ分析について記載してあります。

056-059 凡例の設定

まとめ一覧

凡例操作

library(tidyverse)

graph <- ggplot(diamonds) + geom_histogram(aes(x = price, fill = clarity))
graph
  • まず、凡例をけしてみる guide = FALSE
graph + scale_fill_discrete(guide = FALSE)
  • タイトルをいじる
graph
graph + scale_fill_discrete(name = "透明度")
  • 表示される順番を変えてみる
graph
graph + 
  scale_fill_discrete(breaks = c("I1", "IF", "VVS1",
                                 "VVS2", "VS2", "VS1", "SI2", "SI1"))
  • ところで、ダイヤモンドの透明度について知らないことに気づいたので、調べてみました。

  • 透明度とは、ダイヤモンドに含まれる微少な包有物

    • I1:含まれる
    • SI2:わずかに含まれる
    • SI1:わずかに含まれる
    • VS2:ほんのわずかに含まれる
    • VS1:ほんのわずかに含まれる
    • VVS2:ごくごくわずかに含有
    • VVS1:ごくごくわずかに含有
    • IF:内部が無傷
  • ラベルをつけます

levels(diamonds$clarity)  * で表示された順番に、

text_label_of_clarity <- c("含まれる",
                           "わずかにSI2","わずかにSI1",
                           "ほんのわずかにVS2","ほんのわずかにVS1",
                           "ごくごくわずかにVVS2","ごくごくわずかにVVS1",
                           "内部が無傷")

graph
graph + scale_fill_discrete(labels = text_label_of_clarity)
  • ここまでの情報をまとめると
ggplot(diamonds) + 
  geom_histogram(aes(x = price, fill = clarity)) +
  labs(title = "値段と含有物のヒストグラム", x = "値段", y = "件数") +
  scale_fill_discrete(name = "透明度", 
                      labels = text_label_of_clarity)
  • こんなグラフがかけるようになりました!

  • 練習問題:次のグラフにタイトルと軸のラベルをつけて、透明度の凡例をつけてください。

ggplot(diamonds) + geom_point(aes(carat, price, color = clarity))
  • 答え:
ggplot(diamonds) + geom_point(aes(carat, price, color = clarity))

levels(diamonds$clarity) * で表示された順番に、

text_label_of_clarity <- c("含まれる",
                           "わずかにSI2","わずかにSI1",
                           "ほんのわずかにVS2","ほんのわずかにVS1",
                           "ごくごくわずかにVVS2","ごくごくわずかにVVS1",
                           "内部が無傷")

ggplot(diamonds) + 
  geom_point(aes(carat, price, color = clarity)) +
  labs(title = "値段と重さと透明度の関係", x = "重さ(カラット)", y = "値段") +
  scale_color_discrete(name = "透明度",
                       labels = text_label_of_clarity)

まとめ一覧