我有一个数据框“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
任何帮助将不胜感激。 谢谢
最佳答案
对因素重新排序
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))
关于r - 如何更改 ggplot2 构面的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49899417/