裏 RjpWiki

Julia ときどき R, Python によるコンピュータプログラム,コンピュータ・サイエンス,統計学

ggplot を「けなしまくる」スレッド

2019年12月09日 | ブログラミング

(第2回)Rを使ったグラフィック -ggplot2-

これは,ggplot が悪いんじゃなくて,使った人がうっかりさん。

> 最後に、グラフの外観なんかも帰れたりします。「theme」という関数があって、それで変更します。

#normal p1=ggplot(diamonds2,aes(carat,price,colour=color))+geom_point() #bold grid p2=ggplot(diamonds2,aes(carat,price,colour=color))+geom_point()+theme(panel.grid=element_line(size=2)) #white-black theme p3=ggplot(diamonds2,aes(carat,price,colour=color))+geom_point()+theme_bw() #use ggtheme library(ggthemes) p4=ggplot(diamonds2,aes(carat,price,colour=color))+geom_point()+theme_wsj() grid.arrange(p1,p2,p3,p4,nrow=2)

左の図が正しくて,右が間違い。右のグラフはおうぎ形の半径が量を表している。二次元なんだから面積が量を表すようにしないと,間違った印象を与えるグラフになる(つまり,量の平方根を半径としておうぎ形を描きなさいということ)

見た目が派手(素人受けする)だからといって安易に外観を選んじゃダメ。

  • 背景色が灰色は止めて
  • グリッド線はいらない(図からデータを読もうと思わないし,読めない)
  • 凡例は図中に(とくにこんなに種類が多いし,この場合は単に順番 1,2,3,...)
  • 凡例が図中にないから派手な色使いになる
  • 図の大きさに比して文字が小さい(読めない--読む必要がない)

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

図を描くときに「やるべきこと」と「やってはいけないこと」(その5)

2019年12月09日 | ブログラミング

* Data Visualization: Chart Dos and Don'ts

* Doing the Line Charts Right

折れ線グラフ

左は ggplot をほとんどデフォルトのまま描いたもの

右は base の matplot を使って描いたもの

  • グリッドラインも背景も不要
  • 凡例はわかりやすい場所に分かりやすく付ける
  • その図で何を言いたいか(重要性,妥当性,面白さ etc.)をはっきりさせる

library(ggplot2)
library(ggsci)
library(reshape2)

x <- matrix(c(120, 118, 123, 120, 121, 119, 118, 121, 120, 120,
              121, 135, 145, 158, 173, 184, 198, 214, 209, 212,
              121, 130, 141, 148, 157, 168, 177, 189, 201, 210,
              119, 120, 120, 123, 125, 127, 141, 163, 180, 224,
              120, 128, 137, 144, 153, 163, 171, 179, 187, 199), ncol = 5)
rownames(x) <- 1:10
colnames(x) <- c("A", "B", "C", "D", "E")
y <- melt(x)
colnames(y) <- c("day", "treat", "weight")


ggplot(y, aes(x = day, y = weight, color = treat)) +
    geom_line() +
    scale_color_nejm()

matplot を使う場合,y <- melt(x) のような操作は不要である。

old = par(mar = c(3, 3, 0.5, 3), mgp = c(1.8, 0.4, 0))
color = rep("gray", 5)
lwd = rep(1, 5)
color[4] = "red"     # 強調のため
lwd[4] = 2           # 強調のため
delta.pos = rep(0, 5)
delta.pos[2] = 4     # 凡例位置の調整
delta.pos[3] = -2    # 凡例位置の調整
matplot(x,
    type="l",        # 折れ線グラフを描く
    col = color,     # 線の色
    lwd = lwd,       # 線の太さ
    lty = 1,         # 線の種類(実線)

    tck = -0.02,     # ティックマークの長さ
    las = 1,         # 縦軸目盛りを水平に
    xlab = "day",    # 横軸の名前
    ylab = "weight", # 縦軸の名前
    bty = "l")       # 枠は描かない
text(11, x[10, ] + delta.pos, paste("treat", LETTERS[1:5], sep = "-"),
    col = color, xpd = TRUE)
par(old)

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

PVアクセスランキング にほんブログ村

PVアクセスランキング にほんブログ村