无法根据需要订购填充颜色

时间:2015-11-21 11:23:09

标签: r ggplot2

我需要使用两个单独的geom_area命令生成一个绘图,以便在上面绘制一些时间序列,在零线下面绘制一些时间序列。这是一个简单的例子:

library("reshape2")
library("ggplot2")

d <- as.data.frame(t(read.table(sep=";",header=F,row.names=1,text="
year;1999;2000;2001;2002;2003;2004;2005;2006;2007;2008;2009;2010;2011;2012
primary balance;-5.63;-11.88;-15.37;-18.3;-20.09;-21.45;-21.87;-23.25;-26.98;-29.56;-28.92;-28.46;-29.64;-32.61
snow-ball effect;1.61;0.81;2.67;4.99;7.23;8.02;9.45;9.6;11.01;14.06;22.81;24.41;25.76;26.89
adjustment;2.83;5.38;6.52;3.93;2.28;2.45;3.94;5.28;4.5;6.73;6.94;7.59;7.73;8.07")))
dd <- melt(d,id.vars="year")
dd1 <- subset(dd,variable=="primary balance")
dd2 <- subset(dd,variable!="primary balance")
ggplot()+
  geom_area(data=dd1,aes(x=year,y=value,fill=variable,order=variable),alpha=.5)+
  geom_area(data=dd2,aes(x=year,y=value,fill=variable,order=variable),alpha=.5)

情节是: plot

虽然变量的等级顺序是:(1)“主要平衡”,(2)“雪球效应”和(3)“调整”,现在我可以告诉ggplot指定颜色并放置图例中的项目顺序正确。

3 个答案:

答案 0 :(得分:3)

您可以使用scale_fill_manual(values=..., breaks=...)更改订单:

ggplot() +
geom_area(data=dd1,
          aes(x=year, y=value, fill=variable, order=variable), 
          alpha=.5) +
geom_area(data=dd2,
          aes(x=year, y=value, fill=variable, order=variable),
          alpha=.5) +
scale_fill_manual(values=scales::hue_pal()(3),
                  breaks=c("adjustment",
                           "snow-ball effect",
                           "primary balance"))

plot

答案 1 :(得分:2)

dd <- melt(d,id.vars="year")
o <- ordered(c("primary balance","snow-ball effect","adjustment"), c("primary balance","snow-ball effect","adjustment"))
dd$variable <- ordered(dd$variable, o)
dd1 <- subset(dd,variable=="primary balance")
dd2 <- subset(dd,variable!="primary balance")
p <- ggplot()+ geom_area(data=dd1,aes(x=year,y=value,fill=variable), alpha=.5)
p <- p +  geom_area(data=dd2,aes(x=year,y=value,fill=variable), alpha=.5)
p <- p + scale_fill_manual(values = setNames(scales::hue_pal()(length(levels(dd$variable))), o),
                           breaks = o)
p

你想要那样吗?问题是ggplot按字母顺序排序因子。所以颜色可能会改变。使用ordered生成一个因子并告诉其级别如何排序。 enter image description here

答案 2 :(得分:1)

您可以使用scale_fill_manual手动选择颜色并确定图例中的排序。

ggplot()
+geom_area(data=dd1,aes(x=year,y=value,fill=variable,order=variable),alpha=.5)
+geom_area(data=dd2,aes(x=year,y=value,fill=variable,order=variable),alpha=.5)
+scale_fill_manual(values=c("primary balance"="yellow","snow-ball effect" = "violet","adjustment" = "green"),breaks = levels(dd$variable))

enter image description here