如何在x轴内重新排序填充因子?

时间:2017-09-18 19:35:31

标签: r ggplot2

我想以特定的方式对x轴上的分组进行重新排序,以便每个“月”的“网站”的顺序是BTH,FOX,MEF,DUR。截至目前,网站按字母顺序排序。

Site Month N flux N flux_SE
BTH May 0.047 0.009
BTH Jun 0.974 0.14
BTH Jul 0.698 0.124
BTH Aug 0.112 0.017
BTH Sep 0.107 0.019
BTH Oct 0.234 0.018
FOX May 0.072 0.02
FOX Jun 0.562 0.094
FOX Jul 0.250 0.056
FOX Aug 0.097 0.017
FOX Sep 0.105 0.015
FOX Oct 0.409 0.078
MEF May 0.072 0.025
MEF Jun 0.434 0.167
MEF Jul 0.224 0.058
MEF Aug 0.132 0.047
MEF Sep 0.073 0.024
MEF Oct 0.271 0.08
DUR May 0.039 0.01
DUR Jun 0.342 0.155
DUR Jul 0.175 0.044
DUR Aug 0.065 0.018
DUR Sep 0.061 0.021
DUR Oct 0.279 0.067


flux$Month = factor(N_flux$Month, levels = month.abb)  #This will get the motnhs in chronological order using 3-letter month abbreviations

ggplot(N_flux, aes(x=Month, y=N.flux, fill=factor(Site), reorder(month,month.name))) + #this code makes a 4-panel bar graph by site
  geom_bar(stat="identity", colour="black",position=position_dodge(.9)) +
  scale_y_continuous(expand = c(0,0), limits = c(0,1.5), breaks = seq(0,1.5, by=.2)) +    
  ylab(expression("Nitrogen flux (g N m"*{}^-2*")")) + xlab("Month") + labs(fill = "Site") +
  theme_bw() +
  theme(panel.border = element_rect(color = "black", fill = NA),
        strip.text.x = element_text(colour = 'black', size = 15, face = "bold"),
        axis.text = element_text(colour = "black"),
        panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        legend.position = c(0.9,0.82), legend.text = element_text(size = 9),
        legend.key.size = unit(.55, "cm")) +
  scale_fill_manual(values = c("black", "grey70","grey50", "white")) +
  geom_errorbar(aes(ymin=N.flux, ymax=N.flux+N.flux_SE), size=0.5,                          
                width=.25,position=position_dodge(.9))

Figure I have so far...

1 个答案:

答案 0 :(得分:3)

您只需将列设置为一个因子,就像您在月中所做的那样,并指定级别。添加此行。

N_flux$Site = factor(N_flux$Site, levels = c("BTH", "FOX", "MEF", "DUR"))

然后,您可以更改ggplot命令的第一行。

ggplot(N_flux, aes(x=Month, y=N.flux, fill=Site, reorder(month,month.name))) +

由于它已经是一个因素,因此无需再次创建因子。

enter image description here