Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display the x-axis on ggplot as month only in R

Tags:

I have a very simple question here. I have a dataset from 2009-2012. I want to plot the data with facets. I have created the faceted plot as follows.

R-code

ggplot(al02428400,aes(x=date,y=as.numeric(Discharge)))+geom_line()+ylab("Discharge(cfs)")+facet_wrap(~Year,scales=("free_x"))+theme_bw() 

The output of the above R code is as follows:

enter image description here

On the X-axis I only want to show the month. By default it is showing month and year. Is there any way I can get rid of year ?

The fully reproducible code is as follows:

library(ggplot2)  url <- "http://nwis.waterdata.usgs.gov/usa/nwis/uv/?cb_00060=on&cb_00065=on&format=rdb&period=&begin_date=2009-01-01&end_date=2012-12-31&site_no=02428400" download.file(url,destfile="Data load for stations/data/alabamariver-at-monroeville-2009.txt")  al02428400 <- read.table("Data load for stations/data/alabamariver-at-monroeville-2009.txt",header=T,skip=1,sep="\t") head(al02428400)  sapply(al02428400,class) al02428400 <- al02428400[-1,]  names(al02428400)<- c("Agency","SiteNo","Datetime", "TZ","Discharge","Status","Gageheight","gstatus") al02428400$date <- strptime(al02428400$Datetime, format="%Y-%m-%d %H:%M")  al02428400$Discharge <- as.numeric(as.character(al02428400$Discharge)) al02428400$Year <- as.numeric(format(al02428400$date, "%Y")) ggplot(al02428400,aes(x=date,y=as.numeric(Discharge)))+geom_line()+ylab("Discharge(cfs)")+facet_wrap(~Year,scales=("free_x"))+theme_bw() 

Thanks.

like image 687
Jd Baba Avatar asked May 16 '13 20:05

Jd Baba


People also ask

What does %>% do in Ggplot?

%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Adding things to a ggplot changes the object that gets created. The print method of ggplot draws an appropriate plot depending upon the contents of the variable.

How do I stop Ggplot from scientific notation?

The scale_x_continuous() and scale_y_continuous() methods can be used to disable scientific notation and convert scientific labels to discrete form.

How do I change X label to R in Ggplot?

Changing axis labels To alter the labels on the axis, add the code +labs(y= "y axis name", x = "x axis name") to your line of basic ggplot code. Note: You can also use +labs(title = "Title") which is equivalent to ggtitle .

How do you change the x and y axis in ggplot2?

Use scale_xx() functions It is also possible to use the functions scale_x_continuous() and scale_y_continuous() to change x and y axis limits, respectively.


1 Answers

As your x values are date you can use scale_x_date() to change format of labels. Library scales is needed to get better formatting of breaks and labels.

library(scales) +scale_x_datetime(labels = date_format("%b")) 
like image 113
Didzis Elferts Avatar answered Oct 06 '22 22:10

Didzis Elferts