X axis dates not in chronological order

Viewed 138

I'm a massive Rstudio novice so I have scoured the related questions etc. but I am still having trouble with organising my graph properly. I am having trouble getting my graph to show dates in the correct, chronological order. Wondering if I could get someone to have a look at my code and data and see what i'm doing wrong (explained very simply please, I am a novice).

I am currently reading in a CSV file, which is set up like this 1:

AdD = date sample taken, AdT = time sample taken, AdV = Concentration value - these are water samples and only consist of these two samples across the two months (one per month)

and I get the graph:

The graph shows the 5th month first on the x axis, when I want it in chronological order (aka April - 4th month) to appear first.

My code is as follows (please disregard the geom_hline and axis elements blank - this is one of 6 graphs in a facet and those aren't relevant to the date problem I think/hope) :

F1ambH <- read_csv("data 1 Amb.csv")

f1ambH <- ggplot(data=F1ambH, aes(x=AhD, y=AhV))+  geom_point() +theme_bw()+labs(y= "Concentration (µg/L)", x = "Sample Date") 

f1ambH <- f1ambH + geom_hline(yintercept=1.1, linetype="dashed", color="steelblue")+ theme(axis.title.x = element_blank())+ theme(axis.title.y = element_text(face = "bold", size = 11))

f1ambH

I have also tried mutating the data like this:

F1ambH <- read_csv("data 1 Amb.csv") %>% mutate(dates = dmy(AhD))

f1ambH <- ggplot(data=dates, aes(x=AhD, y=AhV))+  geom_point() +theme_bw()+labs(y= "Concentration (µg/L)", x = "Sample Date") 

which produces this graph:

Which shows the dates correctly, but the two points on the graph don't have a corresponding x axis tick which I need (of which I feel like ive exhausted my options in trying to fix

so if I can fix either problem then that would be amazing.

EDT: Using the +scale_x_date(breaks=unique(F1ambH$dates)) as suggested by the first comment seems to solve my problem, but the points are now at the opposite side of the graph and look horrendous, is there a way to clean it up? Figure

2 Answers

Use your second solution, but use

+scale_x_date(breaks=unique(dates))

to specify where you want the breakpoints.

If you make x variable as factor and add it before plot, it keeps the order:

F1ambH$AhD <- factor(F1ambH$AhD,levels=unique(F1ambH$AhD),order=TRUE)

f1ambH <- ggplot(data=F1ambH, aes(x=AhD, y=AhV))+  geom_point() +theme_bw()+labs(y= 
         "Concentration (µg/L)", x = "Sample Date") 

f1ambH <- f1ambH + geom_hline(yintercept=1.1, linetype="dashed", color="steelblue")+ 
       theme(axis.title.x = element_blank())+ theme(axis.title.y = element_text(face = 
            "bold", size = 11))

f1ambH

Even you can have any order you prefer:

F1ambH$AhD <- factor(F1ambH$AhD,levels=c(your preference order),order=TRUE)
Related