简体   繁体   中英

time series plot with x axis in “year”-“month” in R

I have a "monthly data" I want to plot the data such that I get a date in the format %Y-%m" (2001-01) on the x-axis. Say my data is pcp <- rnorm(24) .

I have tried:

PCP <- ts(pcp, frequency = 12, start = 2001)
plot(PCP) 

but the plot only has years on the x-axis.

How do I get a plot with the date format I desire on the x-axis?

Here's an idea with toy data since the question is not reproducible. Hopefully it helps

R> foo = ts(rnorm(36), frequency = 12, start = 2001)
R> plot(foo, xaxt = "n")
R> tsp = attributes(foo)$tsp
R> dates = seq(as.Date("2001-01-01"), by = "month", along = foo)
R> axis(1, at = seq(tsp[1], tsp[2], along = foo), labels = format(dates, "%Y-%m"))

产量

ggplot version with data that looks like yours

R> df = data.frame(date = seq(as.POSIXct("2001-01-01"), by = "month", length.out = 36), pcp = rnorm(36))
R> library(ggplot2)
R> library(scales)
R> p = ggplot(data = df, aes(x = date, y = pcp)) + geom_line()
R> p + scale_x_datetime(labels = date_format("%Y-%m"), breaks = date_breaks("months")) + theme(axis.text.x = element_text(angle = 45))

在此输入图像描述

I find that the excellent xts package is the best way to store your data. If you've not got it, you can download with install.packages('xts') .

Let's start from basics -- including making pcp , as you've not supplied it.

require(xts)
pcp <- rnorm(24)
PCP <- ts(pcp, frequency = 12, start = 2001)
plot(as.xts(PCP), major.format = "%Y-%m")

This gives you a chart something like the following. You can tweak the dates by altering the string passed to major.format . For example, "%b-%y" yields dates in the Jan-01 format for Jan 2001.

示例情节

The best way is to use axis.POSIXct {graphics} Here the example from the help of this function:

with(beaver1, {
time <- strptime(paste(1990, day, time %/% 100, time %% 100),
                 "%Y %j %H %M")
plot(time, temp, type = "l") # axis at 4-hour intervals.
# now label every hour on the time axis
plot(time, temp, type = "l", xaxt = "n")
r <- as.POSIXct(round(range(time), "hours"))
axis.POSIXct(1, at = seq(r[1], r[2], by = "hour"), format = "%H")
})

in your case change the format to format="%Y-%m"

Regards,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM