blue-sky
blue-sky

Reputation: 53806

How to display labels on x axis?

Here is my .csv file :

dateval,links
18/03/2013,100
19/03/2013,200
20/03/2013,300
21/03/2013,400
22/03/2013,500

This file is read into an object named date1 and this is the code I'm using to graph the data :

g_range <- range(0, date1$links)
plot(date1$links, type="o", col="blue", ylim=g_range,
    axes=FALSE, ann=FALSE)
axis(1, xlab=date1$links)
box()
title(main="Additions", col.main="red", font.main=4)
axis(2, las=1, at=50*0:g_range[2])
title(xlab="Date", col.lab=rgb(0,0.5,0))
title(ylab="# Links", col.lab=rgb(0,0.5,0))

Here is the generated graph :

enter image description here

The date values are not being outputted, instead the numbers 1 - 5 are displayed. How can I modify the code so that it generates the date values contained in the .csv file ? I think the problem is with this line : axis(1, xlab=date1$links) ?

Upvotes: 1

Views: 192

Answers (1)

joran
joran

Reputation: 173527

Try this instead:

axis(1,at=1:5,labels = date1$dateval)

So, you'll note that if you look carefully at ?axis you'll see that there is no xlab argument at all, but the second and third arguments are:

at - the points at which tick-marks are to be drawn. Non-finite (infinite, NaN or NA) values are omitted. By default (when NULL) tickmark locations are computed, see ‘Details’ below.

labels - this can either be a logical value specifying whether (numerical) annotations are to be made at the tickmarks, or a character or expression vector of labels to be placed at the tickpoints. (Other objects are coerced by as.graphicsAnnot.) If this is not logical, at should also be supplied and of the same length. If labels is of length zero after coercion, it has the same effect as supplying TRUE.

But really maybe you should be doing something more like this:

date1$dateval <- as.Date(date1$dateval,format = "%d/%m/%Y")
plot(date1$dateval,date1$links, type="o", col="blue", ylim=g_range, ann=FALSE,axes = FALSE)
axis(1,at=date1$dateval,labels = date1$dateval)

But even that is kind of a crude way to handle plotting dates compared to using packages/functions specifically designed for that purpose.

Upvotes: 1

Related Questions