在 ggplot2 X 轴中重新排序月份

问题描述

我正在做一些降雨分析,我想显示降雨的季节性,我使用我写的以下精灵创建了一个分面包裹图。

#Libraries
library(ggplot2)
library(reshape)
library(RColorBrewer)
library(colorRamps)

#Load data
df <- read.csv('SampleData.csv')
view(df)
#Define x aethetics
df$date <- as.Date(df$date,format = '%m/%d/%Y')
df$month <- month.abb


df1<- melt(df,id=c("month","date"))

df1

#set breaks
breaks <- c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")

#Define color pallet
colourCount = length(breaks)
getPalette = colorRampPalette(brewer.pal(9,"OrRd"))

#Plot
ggplot(df1,aes(date,value,fill=as.factor(month)))+
  geom_bar(position="dodge",stat="identity")+ 
  scale_x_date(date_breaks = "1 month",date_labels = "%b",expand = c(0,0))+
  scale_fill_manual(values = colorRampPalette(brewer.pal(9,"RdGy"))(colourCount),breaks = breaks,name = "Legend")+
  labs(x = "Date: [Months]",y = "Precipitation [mm/month]")+
  facet_wrap(~variable,nrow=2)+
  theme(strip.text = element_text(size =11.5,face="bold"),legend.title = element_text(colour = "black",size =11,legend.text = element_text(colour = "black",size =9),axis.title.y = element_text(colour = "black",axis.text.y = element_text(colour = "black",axis.title.x = element_text(colour = "black",axis.text.x = element_text(colour = "black",size =9))

此任务的示例数据如下。

date,month,Dodoma Airport,Kilosa Agriculture,Morogoro Agriculture,Nongwe Prs
1/1/2020,1,134.31,123.57,109.39,187.97
2/1/2020,2,106.01,105.13,91.33,103.92
3/1/2020,3,110.96,177.46,142.06,175.89
4/1/2020,4,51.2,215.9,196.27,290.39
5/1/2020,5,4.31,69.58,82.07,145.45
6/1/2020,6,0.16,17.06,17.75,25.28
7/1/2020,7,0.01,7.87,11.43,15.03
8/1/2020,8,14.1,7.84,17.32
9/1/2020,9,0.08,12.66,10.97,20.53
10/1/2020,10,3.88,32.95,34.83,29.21
11/1/2020,11,25.2,81.8,55.58,114.12
12/1/2020,12,127.9,158.3,107.75,133.32

输出为流

enter image description here

我想要的是绘制数据,使其从 十月(十月) 开始作为水年的开始,而不是一月(一月),就像现在一样.

我不知道从哪里开始。

帮助。

解决方法

您需要对因子的水平重新排序。

df1$month <- factor(df1$month,levels = c("Oct","Nov","Dec","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep"))

那么你也不需要fill=as.factor(month)