2017-01-02 15 views
1

データを3つのレベル( "catg")の積み上げ棒としてプロットしようとしていますが、 X軸の「低」のサブカテゴリーのその値によって昇順に登場する、ここスタックバープロットxカテゴリをggplot2/Rの塗りつぶしカテゴリの1つの値で並べ替える方法

は生殖例です。

#creating df: 
set.seed(33) 
df<-data.frame(value=runif(12), 
       catg=factor(rep(c("high","medium","low")), 
          levels = c("high","medium","low")), 
       var_name=(c(rep("question1",3),rep("question2",3),rep("question3",3),rep("question4",3))) 
#plotting 
bar_dist<-ggplot(df,aes(x=var_name, 
           y=value, 
           fill=catg, 
          label=round(value,2))) 

bar_dist+ geom_bar(stat = "identity", 
        position = "dodge", 
        width = 0.7)+ 
    coord_flip() + 
    xlab("questions")+ 
    ylab("y")+ 
    geom_text(size = 4,position=position_dodge(width = 0.7)) 

そして、ここでは私の現在のプロットである:

enter image description here

+0

var_nameを要素にし、必要な順番でレベルを設定します。 'reorder'が助けます。たとえば、http://stackoverflow.com/questions/23886472/reorder-data-in-ggplot –

+0

をよく読んでいただき、ありがとうございます。正しくお分かりいただければ、因子のレベルを手動で特定の順序に並べることをお勧めします。私はむしろ他の状況に一般化することができる解決策を見つけるだろう、一般化できる方法であなたの方法を適用する方法があるのだろうか?そこには良い方法がありますか? – Nooga

答えて

2

一つの方法は、可能性があり、したがってこの場合には、私はquestion3、その後、4、1を持っている必要があり、最終的に2 すべてのヘルプは高く評価されます。

df$var_name=factor(df$var_name,levels=rev(levels(reorder(df[df$catg=="low",]$var_name,df[df$catg=="low",]$value)))) 

それはreorder()を使用していますリチャードにより示唆されるようにフィルタリング後にdf$valueに準拠してレベルを並べ替えるにはdf"low"のみを使用してください。
levels()は、前の関数からレベルを抽出するために使用されます。
rev()は、レベルを逆転させるために使用されます。
factor()df$var_name

以上にレベルを再割り当て:これは、(値を減少させることによって)df$valuedfをソート

df$var_name=factor(df$var_name,levels = df[with(df,order(value,decreasing = T)) ,][df[with(df,order(value,decreasing = T)) ,]$catg=="low",]$var_name) 

"low"ためdf$catgにフィルタリングし、factor()のレベルとして使用されるdf$var_nameを取り出します。

同じプロット関数は、次に使用される:

enter image description here

+0

これはまさに私が探していたものです! – Nooga

1

forcatsライブラリからfct_reorder2()を使用してデータ・フレームを変更しない溶液、:

library(forcats) 

bar_dist <- ggplot(df, 
        aes(
        x = fct_reorder2(var_name, catg, value), 
        y = value, fill = catg, 
        label = round(value, 2))) 

bar_dist + geom_bar(stat = "identity", 
        position = "dodge", 
        width = 0.7) + 
    coord_flip() + 
    xlab("questions") + 
    ylab("y") + 
    geom_text(size = 4, position = position_dodge(width = 0.7)) 

Grouped barplot with columns ordered by value of one variable across groups

関連する問題