2016-09-21 5 views
0

私はいくつかの変数は常に負の値を持ち、またいくつかは常に正の値を持つデータセットを持っています。私は負の値が上記のx軸と正の値の下に積み重なった積み重ね領域プロットを作成したいと思います。私は凡例に表示したいデータフレーム内の特定の順序で要素として変数名を持っています。問題は、x軸の上下にデータをプロットするために、geom_area()を2回、データの正のサブセットで1回、負のサブセットで1回使用する必要があるということです。私がこれをするとき、それは元の順序を無視して、伝説の要因を現実化します。プロットされたデータが2つの別々のデータフレームに由来する場合、凡例の要素の順序を指定します。

include('ggplot2') 

test <- data.frame(x=rep(c(1,2,3,4),4), 
        fact=factor(c(rep('a',4),rep('b',4),rep('c',4),rep('d',4)), 
           levels=c('c','a','d','b'), ordered=TRUE), 
        y=c(4,3,2,1,-4,-3,-2,-1,8,6,4,2,-8,-6,-4,-2)) 

# The legend displays the factors in the order I want (c,a,b,d) 
ggplot(data=test, mapping=aes(x=x, y=abs(y)))+ 
    geom_area(mapping=aes(fill=fact)) 

# This doesn't work for plotting above and below the x axis, 
# so I have to split it into two different geom_area calls. 
ggplot(data=test, mapping=aes(x=x, y=y))+ 
    geom_area(mapping=aes(fill=fact)) 

# Factors in legend are now reordered alphabetically, 
# but I want them to be ordered c,a,b,d. 
ggplot(data=test, mapping=aes(x=x, y=y))+ 
    geom_area(data=test[test$y<0,], mapping=aes(fill=fact), stat='identity')+ 
    geom_area(data=test[test$y>0,], mapping=aes(fill=fact), stat='identity') 

私が望むように凡例の要素を表示するにはどうすればよいですか?

答えて

0

は手動breaksを指定することができます。

+ scale_fill_hue(breaks = c('c','a','b','d')) 
関連する問題