!! グラフの見出しなどを指定する ggplot()のオブジェクトの中でテキストで指定できるものは、ほぼ '''labs()''' のオプションで指定できる。 ggplot2::ggplot(data = df) + aes(x = X, y = Y) + geom_point(aes(fill = Hoge)) + geom_line(aes(color = Moge)) + labs( title = "グラフのタイトル", subtitle = "グラフのサブタイトル", caption = "グラフのキャプション", x = "X軸の見出し", y = "Y軸の見出し", fill = "レジェンドの塗りつぶしの見出し default:Hoge", color = "レジェンドの色の見出し default:Moge" ) !! レジェンドのテキストをかえる レジェンドの見出しと同じように、要素(color, fill, ...)に対応する、scale_要素_manual() で設定できる。 d = tibble(V1 = runif(20, -1, 1), V2 = runif(20, 0, 1), V3 = sample(1:4, size = 20, replace = T)) d %>% mutate(V4 = factor(V3)) %>% ggplot() + aes(x = V1, y = V2, color = V4) + geom_point() + scale_x_continuous(breaks = c(-1, 0, 1), limits = c(-1, 1)) + #x軸の表示範囲と表示ラベルを指定 scale_y_continuous(breaks = c(-1, 0, 1), limits = c(-1, 1)) + scale_color_manual(labels = c("A", "B", "C", "D"), values = c(1,2,3,4)) + #レジェンドのラベルを指定 coord_fixed(ratio = 1) #y/x でグラフの縦横比を決める 以下のように、labelsに名前付きベクトルを与えることもできる。 scale_color_discrete(labels = c("2" = "B", "1" = "A")) なお、valuesとlabelsの関係は順序がかわってしまうと表示も意図したものにならないため、牽強さを求めるなら以下のようにすると良いらしい([by ill_identified|引用:https://ill-identified.hatenablog.com/entry/2021/07/28/231922])。 つまり、変数と値とを直接対応させたベクトルを作るということだ。 g + scale_color_manual( values = c(Gentoo = "cyan4", Chinstrap = "purple", Adelie = "darkorange"), labels = c(Chinstrap = "ヒゲ", Gentoo = "ジェンツー", Adelie = "アデリー") ) + labs(title = "正しく設定できたグラフ", color = "種")