Ggplot2-diverging-charts
提供:Dev Guides
ggplot2-発散チャート
前の章では、「ggplot2」パッケージを使用して作成できるさまざまなタイプのグラフについて説明しました。 次に、分岐棒グラフ、ロリポップグラフなどのバリエーションに注目します。 まず、分岐棒グラフの作成から始めます。従うべき手順を以下に示します-
データセットについて
必要なパッケージを読み込み、mpgデータセット内に「車名」という新しい列を作成します。
#Load ggplot
> library(ggplot2)
> # create new column for car names
> mtcars$`car name` <- rownames(mtcars)
> # compute normalized mpg
> mtcars$mpg_z <- round((mtcars$mpg - mean(mtcars$mpg))/sd(mtcars$mpg), 2)
> # above/below avg flag
> mtcars$mpg_type <- ifelse(mtcars$mpg_z < 0, "below", "above")
> # sort
> mtcars <- mtcars[order(mtcars$mpg_z), ]
上記の計算では、車名の新しい列を作成し、ラウンド関数を使用して正規化されたデータセットを計算します。 「平均」フラグの上下を使用して、「タイプ」機能の値を取得することもできます。 後で、値をソートして必要なデータセットを作成します。
受信した出力は次のとおりです-
下記のように特定のプロットでソートされた順序を維持するために値を因数に変換します-
> # convert to factor to retain sorted order in plot.
> mtcars$`car name` <- factor(mtcars$`car name`, levels = mtcars$`car name`)
得られた出力は以下に記載されています-
分岐棒グラフ
次に、必要な座標と見なされる前述の属性を持つ分岐棒グラフを作成します。
> # Diverging Barcharts
> ggplot(mtcars, aes(x=`car name`, y=mpg_z, label=mpg_z)) +
+ geom_bar(stat='identity', aes(fill=mpg_type), width=.5) +
+ scale_fill_manual(name="Mileage",
+ labels = c("Above Average", "Below Average"),
+ values = c("above"="#00ba38", "below"="#f8766d")) +
+ labs(subtitle="Normalised mileage from 'mtcars'",
+ title= "Diverging Bars") +
+ coord_flip()
注意-上記の値に関して上または下方向を指しているいくつかのディメンションメンバーの分岐棒グラフマーク。
分岐棒グラフの出力は、棒グラフを作成するために関数geom_barを使用して以下に説明されています-
分岐ロリポップチャート
使用する関数の変更のみを使用して、同じ属性と座標を持つ分岐ロリポップチャートを作成します。 geom_segment()ロリポップチャートの作成に役立ちます。
> ggplot(mtcars, aes(x=`car name`, y=mpg_z, label=mpg_z)) +
+ geom_point(stat='identity', fill="black", size=6) +
+ geom_segment(aes(y = 0,
+ x = `car name`,
+ yend = mpg_z,
+ xend = `car name`),
+ color = "black") +
+ geom_text(color="white", size=2) +
+ labs(title="Diverging Lollipop Chart",
+ subtitle="Normalized mileage from 'mtcars': Lollipop") +
+ ylim(-2.5, 2.5) +
+ coord_flip()
発散ドットプロット
同様の方法で発散ドットプロットを作成します。ここで、ドットは、より大きな次元の散布図の点を表します。
> ggplot(mtcars, aes(x=`car name`, y=mpg_z, label=mpg_z)) +
+ geom_point(stat='identity', aes(col=mpg_type), size=6) +
+ scale_color_manual(name="Mileage",
+ labels = c("Above Average", "Below Average"),
+ values = c("above"="#00ba38", "below"="#f8766d")) +
+ geom_text(color="white", size=2) +
+ labs(title="Diverging Dot Plot",
+ subtitle="Normalized mileage from 'mtcars': Dotplot") +
+ ylim(-2.5, 2.5) +
+ coord_flip()
ここでは、凡例は「平均以上」と「平均以下」の値を表し、緑と赤の異なる色で表示されます。 ドットプロットは静的な情報を伝えます。 原則は、ポイントのみが使用されることを除いて、分岐棒グラフの原則と同じです。