6
5

More than 5 years have passed since last update.

[R]ggplot2で散布図を作成

Last updated at Posted at 2018-12-25

散布図を書いてみたので、超基本的なところのまとめ

環境

  • Windows10
  • R:3.5.2
  • Rstudio

データセット(2018.txt)の一部

順位 チーム 試合 打率 打点 平均 安打
1 レッドソックス 162 0.268 876 5.41 1509
2 カブス 162 0.259 760 4.69 1450
3 インディアンズ 162 0.259 818 5.05 1448

用いたデータセットは2018年のMLBのチーム打撃成績です。実際は30チーム分のデータセットがあります。

データセットの読み込み

table = read.table("2018.txt", sep="\t", header=T,encoding="utf-8")

タブ区切りなので今回は「sep="\t"」としました。

パッケージのインストールと呼び出し

install.packages("ggplot2")
library(ggplot2)

散布図を書く

実際のコードの前にサクッと説明すると

g <- ggplot(データフレーム, aes(x=x軸のカラム名,y=y軸のカラム名))
g <- g + geom_point() #geom_pointは「散布図で書いてね」と指定するため
plot <- g

これに、データフレーム、xとy軸のカラム名を当てはめていく。
今回データフレームは「table」、x軸のカラム名は「順位」、y軸のカラム名は「安打」。

実際のコードはこんな感じ

g <- ggplot(table, aes(x=順位 ,y=安打))
g <- g + geom_point()
plot(g)

実行結果

plot1.png

ラベルを付けてみた

「ggrepel」というパッケージを利用することで、ラベルを付けることができる。
ラベルを付ける方法として「geom_text_repel」と「geom_label_repel」の2つがある。

geom_text_repel

library(ggplot2)
library(ggrepel)
g <- ggplot(table, aes(x=順位 ,y=安打, label=チーム))
g <- g + geom_point() + geom_text_repel()
plot(g)

追加したのは「library(ggrepel)」と 「label = チーム」と「geom_text_repel()」の3ヵ所

実行結果

plot1_label.png

geom_label_repel

「geom_text_repel()」の部分を「geom_label_repel()」に置き換える

library(ggplot2)
library(ggrepel)
g <- ggplot(table, aes(x=順位, y=安打, label=チーム))
g <- g + geom_point() + geom_label_repel()
plot(g)

実行結果

plot1_label2.png

png形式として保存

pngとして保存する場合はpng関数を利用します。ざっくり説明すると、「タイトルとサイズを決める」→「グラフを描く」→「描いたものを閉じる」といった流れです。ちなみに、画像のサイズは決めなくてもできます。

library(ggplot2)
library(ggrepel)
png("plot1_label2.png", width=1000, height=700)
g <- ggplot(table, aes(x=順位, y=安打, label=チーム))
g <- g + geom_point() + geom_label_repel()
plot(g)
dev.off()
6
5
0

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