0

I was wondering if you can reorder the factor levels in termplot, as they are currently in alphabetical order and I require them to be in chronological order.

This was the code I used to create the plot:

termplot(model2, rug=TRUE, se=T, xlabs="Month/Year", ylabs="", ylim=c(-2,3), ask=F, col.term = 1, col.se = 1, use.factor.levels=TRUE)

This produces the plot below: enter image description here

So I would like to reorder it so that Jul/Aug 2015 is first, then Sept/Oct 2015, then April 2016.

I know you can do this fairly simply in ggplot but couldn't find any way of doing this in termplot.

Is there a way to do this?

KernelPanic
  • 600
  • 8
  • 19
jono33
  • 1
  • Apologies, it wouldn't let me upload the plot as I am new to stackoverflow and don't have enough 'reputation points' – jono33 Feb 24 '17 at 02:42
  • See this answer http://stackoverflow.com/questions/42216352/how-to-change-the-order-of-x-axis-in-multiple-boxplots-in-r/42217150#42217150 – Dave2e Feb 24 '17 at 03:01
  • Thank you, however this approach doesn't work for termplot as it is working from the output of the GAM so the levels are already set from this. – jono33 Feb 24 '17 at 04:18

1 Answers1

0

You need to convert the "Month Year" character representations to objects of class "Date". However, in order to do this, you need to tidy your data according to your current locale. In the the English US locale (you can inspect the TIME aspect of your locale by typing Sys.getlocale("LC_TIME") in the console), these are some of the steps you need to take:

First, the correct names of the months and their abbreviations are: January (Jan), February (Feb), March (Mar), April (Apr), May (May), June (Jun), July (Jul), August (Aug), September (Sep), October (Oct), November (Nov), December (Dec). In your data, you have "Sept" when it should be "Sep", which may cause an error while converting.

Second, in order to convert character representations to "Date" objects through base R, a year, a month, and a day must be supplied. This can be solved however through the suggested code below.

Third, your data also disobeys the "year-month-day" format by concatenating two months, e.g. "Jul/Aug 2015". Functions in base R for manipulating date conversions will not accept this format.

In sum, you first need to tidy your data so that it is an acceptable format, then you can produce the plot that you want. Below I have provided code which shows how to convert between acceptable character representations and objects of class "Date" representing calendar dates.

# Set the locale if your current differs from below
Sys.setlocale(category = "LC_TIME", locale = "en_US.UTF-8")

# Convert from character to class "Date"
m <- as.Date(x = paste(c("April 2016", "Jul 2015", "Sep 2015", "March 2017"), "01", sep = " "), format = "%B %Y %d")

If you provide your data set, I can give you more detailed help.

Samuel
  • 2,895
  • 4
  • 30
  • 45