Ggplot2 + Date structure using the X scale

I really need help here because I'm far from lost.

I am trying to create a line chart showing the performance of several teams over the course of a year. I divided the year into a quarter: 1/1/2012, 4/1/12. 8/1/12. 12/1/12 and loaded the csv data frame into R.

Month Team Position 1 1/1/12 South Africa 56 2 1/1/12 Angola 85 3 1/1/12 Morocco 61 4 1/1/12 Cape Verde Islands 58 5 4/1/12 South Africa 71 6 4/1/12 Angola 78 7 4/1/12 Morocco 62 8 4/1/12 Cape Verde Islands 76 9 8/1/12 South Africa 67 10 8/1/12 Angola 85 11 8/1/12 Morocco 68 12 8/1/12 Cape Verde Islands 78 13 12/1/12 South Africa 87 14 12/1/12 Angola 84 15 12/1/12 Morocco 72 16 12/1/12 Cape Verde Islands 69 

When I try to use ggplot2 to generate a chart, the fourth quarter of 12/1/12 inexplicably moves to second place.

 ggplot(groupA, aes(x=Month, y=Position, colour=Team, group=Team)) + geom_line() 

Then I put this graph in a GA variable to try using scale_x to format the date:

 GA + scale_x_date(labels = date_format("%m/%d")) 

But I keep getting this error:

 Error in structure(list(call = match.call(), aesthetics = aesthetics, : 

could not find function "date_format"

And if I run this code:

 GA + scale_x_date() 

I get this error:

 Error: Invalid input: date_trans works with objects of class Date only 

I am using Mac OS X running R 2.15.2

Please, help.

+5
source share
1 answer

This is because df$Month (if your data.frame is df ), which has a factor , has its levels in that order.

 > levels(df$Month) # [1] "1/1/12" "12/1/12" "4/1/12" "8/1/12" 

The solution is to reorder your factor levels.

 df$Month <- factor(df$Month, levels=df$Month[!duplicated(df$Month)]) > levels(df$Month) # [1] "1/1/12" "4/1/12" "8/1/12" "12/1/12" 

ggplot2_factor_levels

Edit: Alternative solution using strptime

 # You could convert Month first: df$Month <- strptime(df$Month, '%m/%d/%y') 

Then your code should work. Check out the chart below:

ggplot2_strptime_solution

+6
source

All Articles