LoginSignup
5
5

More than 5 years have passed since last update.

{ggplot2} 消えたlegendの謎

Last updated at Posted at 2015-10-23

--2015/1026更新--

みんな大好き$ggplot2$ :notes:
みんな大好き$iris$ :notes:

> head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

消えたlegendの謎

例えば、横軸に$Sepal.Length$を取って、縦軸には$Sepal$と$Petal$の2種類の$Width$をプロットしたい。legendも付けたい。

ggplot(iris, aes(x=Sepal.Length))+
  geom_point(aes(y = Petal.Width, color="Petal"))+
  geom_point(aes(y = Sepal.Width, color="Speal"))+
  ylab("Width")

スクリーンショット 2015-10-23 18.03.03.png
おぉ、。legendのタイトルは適当に直せそうだけど、
色いじれるのか?これ。

ggplot(iris, aes(x=Sepal.Length))+
  geom_point(aes(y = Petal.Width, color="Petal"), color="Blue")+
  geom_point(aes(y = Sepal.Width, color="Speal"), color="Red")+
  ylab("Width")

スクリーンショット 2015-10-23 18.04.19.png
ん〜〜〜。legendが消えた;;

もう少し複雑な謎

これを$Species$ごとにグラフを分けたい。

ggplot(iris, aes(x=Sepal.Length, color=Species))+
  hogehoge

じゃぁダメだろうな〜。
colorの指定がダブルになっちゃう。

        ,.-─ ─-、─-、
      , イ)ィ -─ ──- 、ミヽ
      ノ /,.-‐'"´ `ヾj ii /  Λ
    ,イ// ^ヽj(二フ'"´ ̄`ヾ、ノイ{
   ノ/,/ミ三ニヲ´        ゙、ノi!
  {V /ミ三二,イ , -─        Yソ
  レ'/三二彡イ  .:ィこラ   ;:こラ  j{
  V;;;::. ;ヲヾ!V    ー '′ i ー ' ソ
   Vニミ( 入 、      r  j  ,′
   ヾミ、`ゝ  ` ー--‐'ゞニ<‐-イ
     ヽ ヽ     -''ニニ‐  /
        |  `、     ⌒  ,/
       |    > ---- r‐'´
      ヽ_         |
         ヽ _ _ 」

     ググレカス [ gugurecus ]
   (西暦一世紀前半~没年不明)

ggplot2で同一グラフに2変数の折れ線グラフを描きたい

おお!

library(tidyr)

このヒトのお世話になります。

a <- gather(iris, key=low, value=value, -c(Species, Sepal.Length))
ggplot(a, aes(x=Sepal.Length, y=value, color=low))+
  geom_point()+
  facet_wrap( ~Species, scale="free")

スクリーンショット 2015-10-23 18.19.00.png

おおー。yes, yes, yes。

色?

色いじりたい???

君、色いじりたいの???

orz

追記(2015/10/26)

yutannihilation様より下記コメントをいただき、お勉強です。
自由度が上がってきました。ありがとうございますm(_ _)m

ggplot(a, aes(x=Sepal.Length, y=value, color=legend))+
  geom_line(aes(linetype=legend))+
  scale_color_manual(values=c(1,2,4))+
  scale_linetype_manual(values=c(3:1))+
  theme(text = element_text(size=20)) +
  facet_wrap( ~Species, scale="free")

スクリーンショット 2015-10-26 10.52.44.png

その他、使えそうなオプション、

  facet_wrap( ~Species, scale="free_y") # Y軸だけsceleをfree
  theme(legend.position=c(0.7, 0.2)) # 作図画面全体の中での位置
  theme(legend.key.size=unit(2.5, "lines")) # あんま意味分かってない。
     # unitを使うには{grid}が必要

とする。

もう、
スクリーンショット 2015-10-26 19.24.18.png
やりたい放題

5
5
2

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
5
5