r - x-axis labeling with 'non-date' x-values -
i using r produce line graph , have 2 vectors, 1 x value , y value. more concrete it's accumulated performance on time. can plot line using data (data$accbh
). however, when try put data y in code this:
plot(data$date, data$accbh, type='l')
it doesn't work. in documentation read "plot(x, y, ...)" thought need put vector y , x in respective positions. data x 'nondate' dates example 'jan-00'.
basically, want have dates y data show on x axis in stead of 50, 100, 150.. in graph below. found far working 'real dates' in x axis.
i realised can't post images yet. should describe graph first.
it great if me out. also, first question posted, if think should change way post question, please let me know. thank you!
you can't expect r , plot()
make up numeric values arbitrary character strings human understand might gibberish computer!
you need inform r vector date
in data frame represents date - in r parlance object of class "date"
. don't have days there, have make them - first of each month suffice. consider simple example data set
df <- data.frame(date = paste(month.abb, "13", sep = "-"), accbh = rnorm(12))
i inform r date
"date"
object through as.date()
. notice here pasting on 01-
each of month-year combinations in df
. appropriate format
specifier provided tell r how "read" elements of date (read ?strftime
details)
df <- transform(df, date = as.date(paste("01", as.character(df$date), sep = "-"), format = "%d-%b-%y"))
once have data in correct format, shown here str()
function
> str(df) 'data.frame': 12 obs. of 2 variables: $ date : date, format: "2013-01-01" "2013-02-01" ... $ accbh: num 0.494 -0.759 -2.204 -2.004 2.808 ...
plot()
works appropriately:
plot(accbh ~ date, data = df, type = "l")
producing (you'll have different data):
if want different labelling, you'll need specify yourself, e.g.
plot(accbh ~ date, data = df, type = "l", xaxt = "n") with(df, axis.date(side = 1, x = date, format = "%b-%y"))
see ?axis.date
more details.
note there zoo package has data type year-month, "yearmon"
class. can use without fiddling original data
df2 <- data.frame(date = paste(month.abb, "13", sep = "-"), accbh = rnorm(12))
through use of as.yearmon()
function
require("zoo") df2 <- transform(df2, date = as.yearmon(date, format = "%b-%y"))
then create "zoo"
object using variables created
zobj <- with(df2, zoo(accbh, order.by = date))
this gives
> zobj jan 2013 feb 2013 mar 2013 apr 2013 may 2013 jun 2013 -0.607986011 1.741046878 -0.603960213 -1.319397405 -0.355051912 0.296862314 jul 2013 aug 2013 sep 2013 oct 2013 nov 2013 dec 2013 0.235978782 -0.308123299 -0.200230379 -0.004428621 -0.858600654 -0.241808594
which can plotted
plot(zobj)
but note has it's own way of labelling axes.
Comments
Post a Comment