CaitlinG
CaitlinG

Reputation: 2015

Changing the order of values on the x-axis in R

I am attempting to create a line graph (time vs anxiety) in R with the x-axis ranging from 10am to 6pm. R, however, reorders the values in numeric order and the graph looks vaguely 's-shaped'. Please see below for vectors:

anxiety <- c(1, 1, 2, 2, 3.5, 4, 4.5, 5, 5)
time <- c(10, 11, 12, 1, 2, 3, 4, 5, 6)

plot(time, anxiety, xlab='Time (hour of day)', ylab='Degree of anxiety (estimated)', xaxt='n', main='The Effect of Technology Deprivation on Anxiety', col='blue', type='l', cex.lab=1.5, cex.main=1.5, las=1)

I would prefer that the x-axis values be presented in chronological order (10am, 11am, etc.) and that the graph reflect a near linear pattern of increasing anxiety.

Thanks all.

~Caitlin

Upvotes: 3

Views: 4431

Answers (3)

vpipkt
vpipkt

Reputation: 1707

For both this task and further analysis, you may find it more convenient to use R's date-time classes to store the time. This will take a bit of work up front, but also clarify your dataset's meaning later on. For example

time <- strptime(c("6:00 AM","7:00 AM","1:00 PM"),"%I:%M %p")

Note that this will make some inference about the date (today) and time zone (user's local time zone). But if you also have that information, you can include that in the strings, and modify the format argument.

R will then plot the times in a very clear way. See this question for more info on customizing the x-axis label: R plot with an x time axis: how to force the ticks labels to be the days?

Upvotes: 1

Cath
Cath

Reputation: 24074

If you had 12 to each "pm value", you get what you want :

time[4:9]<-12+time[4:9]
plot(time, anxiety, xlab='Time (hour of day)', ylab='Degree of anxiety (estimatee)', xaxt='n', main='The Effect of Technology Deprivation on Anxiety', col='blue', type='l', cex.lab=1.5, cex.main=1.5, las=1)

NB: If you want to put labels in your xaxis, you can use your former variable and so better rename time :

time2<-c(time[1:3],time[4:9]+12)
plot(time2, anxiety, xlab='Time (hour of day)', ylab='Degree of anxiety (estimatee)', xaxt='n', main='The Effect of Technology Deprivation on Anxiety', col='blue', type='l', cex.lab=1.5, cex.main=1.5, las=1)
axis(1,at=time2,labels=time)

Upvotes: 1

KFB
KFB

Reputation: 3501

if you are willing to give ggplot2 a try

# data
anxiety <- c(1, 1, 2, 2, 3.5, 4, 4.5, 5, 5)
time <- c(10, 11, 12, 1, 2, 3, 4, 5, 6)
df <- data.frame(anxiety, time)
# order the level of time
df$time <- factor(df$time, order=TRUE, levels=time)

# plot
ggplot(df, aes(x=time, y=anxiety, group=1)) + geom_line()

enter image description here

Upvotes: 4

Related Questions