如何调整ggplot2图形的分面排列顺序?
嘿,我来帮你搞定ggplot2分面排列顺序的问题!首先得明确:分面的展示顺序完全由你用来分面的变量的因子水平顺序决定,所以核心操作就是调整对应因子的水平排序,再绘制分面图就行。
先回顾下你的数据结构:
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...
调整分面排列顺序的具体步骤
不管你用facet_wrap()还是facet_grid(),都可以按以下方法操作:
1. 重新指定分面变量的因子水平
分面的顺序完全跟着因子的水平走,所以先把你想要的分面顺序定义成因子的水平。
情况1:调整月份(Month)的顺序
现在你的Month因子是从"Dec"开头的,如果想改成自然月份顺序(Jan→Feb→…→Dec),可以这样修改:
pd.long$Month <- factor(pd.long$Month, levels = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
情况2:调整站点(Site)的顺序
如果你想按自定义的站点顺序排列分面,直接把你想要的顺序放进levels参数里就行:
# 替换成你实际需要的站点顺序 pd.long$Site <- factor(pd.long$Site, levels = c("EB", "BED", "BEU", "这里放其他站点名称..."))
2. 绘制分面图验证顺序
调整完因子水平后,再添加分面代码即可。比如用facet_wrap()按站点分面:
ggplot(pd.long, aes(x=Month, y=Density, fill=Site))+ geom_bar(stat = "identity", position = "dodge", fill = "darkgray")+ xlab("Month")+ # 现在分面会按照你指定的Site顺序排列 facet_wrap(~Site)
如果是用facet_grid()做行列分面:
ggplot(pd.long, aes(x=Month, y=Density, fill=Site))+ geom_bar(stat = "identity", position = "dodge", fill = "darkgray")+ xlab("Month")+ # 按Site列排列,或者写成 Site ~ . 按行排列 facet_grid(. ~ Site)
小技巧:不用修改原始数据框的方法
如果你不想改动原始数据,可以直接在分面函数里临时指定因子顺序:
ggplot(pd.long, aes(x=Month, y=Density, fill=Site))+ geom_bar(stat = "identity", position = "dodge", fill = "darkgray")+ xlab("Month")+ # 临时指定Site的分面顺序 facet_wrap(~factor(Site, levels = c("EB", "BED", "BEU", ...)))
这样分面就会完全按照你想要的顺序展示啦!
内容的提问来源于stack exchange,提问作者Muneer
相关产品推荐
相关产品推荐

