如何更改ggplot2构面的顺序 [英] How to change the order of ggplot2 facets

查看:205
本文介绍了如何更改ggplot2构面的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a data frame "pd.long" with following structure:

> 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 ...

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

I have constructed bar-plots with this piece of code:

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按字母顺序对其进行排序,如下所示:

Everything was fine until I noticed that the levels of variable "Site" are not in the order of my choice. ggplot orders them alphabetically, as follows:

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

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

However, I want them to be in the same order in which they appear in the variable column i.e.

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

任何帮助将不胜感激. 谢谢

Any help will highly be appreciated. Thank you

推荐答案

重新排列因素

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

或更一般的答案,其中顺序基于Site列中的第一个出现:

or more general answer where the order is based on the first apperance in the Site column :

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

这篇关于如何更改ggplot2构面的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆