简体   繁体   English

在 ggplot2 X 轴中重新排序月份

[英]Reordering Months in ggplot2 X-Axis

I'm doing some rainfall analysis and I would like to show rainfall seasonality, I have created a facet wrap plots using the following sprit I wrote.我正在做一些降雨分析,我想显示降雨的季节性,我使用我写的以下精神创建了一个分面环绕图。

#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, face="bold"),
        legend.text = element_text(colour = "black", size =9),
        axis.title.y = element_text(colour = "black", size =11, face="bold"),
        axis.text.y = element_text(colour = "black", size =9),
        axis.title.x = element_text(colour = "black", size =11, face="bold"),
        axis.text.x = element_text(colour = "black", size =9))

The sample data for this task is as follows.此任务的示例数据如下。

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,0.01,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

The output is as flows output 如流在此处输入图像描述

What I want is to plot the data so as it start at OCTOBER (Oct) as the start of water year and Not January (Jan) as it is now.我想要的是 plot 数据,以便它从10 月(10 月)开始作为水年的开始,而不是现在的 1 月(1 月)

I don't know where to start.我不知道从哪里开始。

Help.帮助。

You need to reorder the levels of your factor.您需要重新排序因子的水平。

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

then you also don't need fill=as.factor(month)那么你也不需要fill=as.factor(month)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM