2017-10-20 18 views
0

geom_barposition = "dodge"を使用してダイヤモンドの割合をプロットしようとしています。ここに私がしたことがあります。ggplot2:geom_barを使って正しい比率をプロットする

下記の画像は、cutタイプごとにいくつのダイヤモンドがあるかを示しています。

enter image description here

今度は、空想何かをしましょう。

ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut, fill = clarity), position = "dodge") 

下画像は、各cutタイプに対してclarityによってダイヤモンドをグループ化することによってのカウントを提供します。私がやりたい何

enter image description here

は、上記の代わりに、カウントの割合を示すと同じかわすプロットを取得することです。

たとえば、cut=idealおよびclarity = VS2の場合、割合は5071/21551 = 0.23である必要があります。

+1

追加の列は必要ない試すことができます: 'ggplot(データ=ダイヤモンド)+ yのgeom_bar(マッピング= AES(X =カット、= ..countを.. –

+0

@MauritsEversこれは望ましい結果を与えません(例えば、それを実行し、 'cut = ideal'の値を見てください)。 'clarity = VS2' - 0.23ではない)。 – Lyngbakr

+0

@Lyngbakrああ、そうだよ! OPは分数*(カット)グループ*を求めます。私の解は合計の分数を与える。その場合、私はグループごとの分数を手動で計算し、@Wimpelのように 'geom_bar(stat =" identity "、...)'でプロットします。 –

答えて

2

あなたは

library(tidyverse) 
diamonds %>% 
    count(cut, clarity) %>% 
    group_by(cut) %>% 
    mutate(Sum=sum(n)) %>% 
    mutate(proportion = n/Sum) %>% 
    ggplot(aes(y=proportion, x=cut,fill=clarity)) + 
    geom_col(position = "dodge") 

enter image description here

+0

ありがとう、これは私が探していたものです。 –

-1

は(「割合」という名前の)正しい割合でカラムを作成し、マウリッツエバースが示唆するようにあなたはまた、比率をインラインで計算することができ

require(ggplot2) 
require(scales) 

ggplot(data = diamonds) + 
geom_bar(mapping = aes(x = cut, y = percentage, fill = clarity), position = "dodge") + 
scale_y_continuous(labels = scales::percent) 

を使用しています。

+0

割合ではなく割合を求めます。 – Lyngbakr

+0

ああ、そうだね。それを逃した:) – Wimpel

関連する問題