如何更改ggplot2 facets的顺序

时间:2018-04-18 12:11:29

标签: r ggplot2

我有一个数据框" pd.long"具有以下结构:

> str(pd.long)
'data.frame':   144 obs. of  3 variables:
$ Site   : Factor w/ 12 levels "BED","BEU","EB",..: 8 9 10 3 11 1 6 7 5 4 ...
$ Month  : Factor w/ 12 levels "Dec","Jan","Feb",..: 1 1 1 1 1 1 1 1 1 1 ...
$ Density: int  20 20 20 20 20 20 20 20 20 20 ...

我用这段代码构建了条形图:

ggplot(pd.long, aes(x=Month, y=Density, fill=Site))+
geom_bar(stat = "identity", position = "dodge", fill = "darkgray")+
xlab("Month") + ylab("Number")+
facet_wrap(~Site, nrow = 3, scales = "free")

图表看起来像这样:

一切都很好,直到我注意到变量" Site"不是我选择的顺序。 ggplot按字母顺序排序,如下所示:

pd.long$Site
Levels: BED BEU EB KAD KAU KB KER KOA KOB KOO PNS RO

但是,我希望它们与它们出现在变量列中的顺序相同,即

KOA KOB KOO EB  PNS BED KB  KER KAU KAD RO  BEU

任何帮助都将受到高度赞赏。 谢谢

1 个答案:

答案 0 :(得分:5)

重新排序因素

pd.long$Site <- factor(pd.long$Site,levels=c("KOA","KOB","KOO","EB","PNS","BED","KB","KER","KAU","KAD","RO","BEU"))

或更常见的答案,其中订单基于Site列中的第一个外观:

pd.long$Site <- factor(pd.long$Site,levels=unique(pd.long$Site))