2016-09-21 38 views
0

我有一个数据集,其中一些变量总是有负值,有些总是正值。我想制作一个叠加区域图,其中负值叠加在x轴下面和上面的正值上。我在我的数据框中以特定顺序具有变量名称作为因子,我想在图例中显示这些变量名称。问题在于,为了绘制x轴上方和下方的数据,我必须使用geom_area()两次,一次使用数据的正数子集,一次使用负数子集。当我这样做时,它会使传说中的因素实际化,忽略它们的原始顺序。当绘制数据来自两个单独的数据框时,指定图例中的因子顺序。

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')) 
相关问题