问题
How might I plot month to month growth for the following data:
A
2008-07-01 0
2008-08-01 87
2008-09-01 257
2008-10-01 294
2008-11-01 325
2008-12-01 299
(In dput format, before Joshua hunts me down and murders me in my sleep):
structure(c(0L, 87L, 257L, 294L, 325L, 299L), .indexCLASS = c("POSIXt",
"POSIXct"), .indexTZ = "", index = structure(c(1214884800, 1217563200,
1220241600, 1222833600, 1225512000, 1228107600), tzone = "", tclass = c("POSIXt",
"POSIXct")), .Dim = c(6L, 1L), .Dimnames = list(NULL, "A"), class = c("xts",
"zoo"))
回答1:
Define growth: first difference? Percentages? In either case just compute and then plot:
R> index(KB) <- as.Date(index(KB)) ## what you have are dates, not datetimes
R> barplot(diff(KB), ylab="Change in value", main="Growth")
![](https://i0.wp.com/i.stack.imgur.com/PloTu.png)
You can also use a standard line plot:
R> plot(diff(KB), type='b', ylab="Change in value", main="Growth")
![](https://i0.wp.com/i.stack.imgur.com/rRORj.png)
and change the type=
argument of this plot to show bars etc pp. Normally would plot percentage changes but given your first datapoint this is inadmissible here (as noted by Gavin) so diffs it is for this illustration.
回答2:
Using your dput()
data in object dat
, and assuming you mean the month percentage change over previous month, then:
R> (diff(dat) / lag(dat)) * 100
A
2008-07-01 05:00:00 NA
2008-08-01 05:00:00 Inf
2008-09-01 05:00:00 195.40230
2008-10-01 05:00:00 14.39689
2008-11-01 04:00:00 10.54422
2008-12-01 05:00:00 -8.00000
(Forgot the plot)
plot((diff(dat) / lag(dat)) * 100, main = "",
ylab = "% growth (for some definition of % growth)")
![](https://i0.wp.com/i.stack.imgur.com/Fe3DJ.png)
Not sure how best to handle the second month - % growth was infinite...
来源:https://stackoverflow.com/questions/6876928/r-month-by-month-percent-growth-on-an-xts-objects