以手动定义的顺序ggplot绘制熔化变量

时间:2013-11-05 14:10:35

标签: r ggplot2

我有一个有六列的矩阵。我想分别绘制每一列。

首先我创建矩阵:

a<-replicate(6,rnorm(100))
colnames(a)<-c("one", "two", "three", "four", "five","six")

然后我melt()变量:

b<-melt(a, id.vars=1:6)
    colnames(b)<-c("c","variable","value")

现在我想绘制这些变量:

ggplot(b,aes(x = c, y = value, colour = variable, linetype = variable,size = variable)) + 
     geom_line() + 
     scale_x_continuous(breaks=seq(0,100,5)) +
     scale_colour_manual(values=c("blue1", "blue1","blue1","blue1","blue1","blue1")) + 
     scale_linetype_manual(values = c(0,0,1,0,0,0)) + 
     scale_size_manual(values = c(0.2,0.2,0.2,0.2,0.2,0.2)) + 
     xlab("\nT") + 
     ylab("O\n") +
     theme_bw()

然而,不是按照指定的“一”,“二”,“三”等顺序绘制变量,而是将顺序混合为:五四有一六三二。如何按指定列名的顺序绘制变量?

2 个答案:

答案 0 :(得分:3)

b$variable会显示该列的因子级别。这就是ggplot正在采取的顺序。您可以更改此类级别 - b$variable <- factor(b$variable, levels =c("one","two","three","four","five","six"))

答案 1 :(得分:0)

您需要更改因子级别的顺序,以便手动定义沿x轴的顺序。

  

b $ c&lt; - factor(b $ c,levels = c(“one”,“two”,“three”,“four”,“five”,“six”))

请注意,如果您使用图例,这也会决定图例中项目的顺序。但是,图例中的项目顺序也可以使用scale_fill_discrete(limits = c("item1", "item2"))

进行设置