简体   繁体   中英

Issue with x-axis labels in a time-series plot

I want to plot data from a time-series object and properly customise the labels that are shown in the x-axis.

The data I am plotting correspond to monthly values, from January 2017 to December 2017.

I've read other similar posts on the same subject here, and I have tried everything I imagined, but I can't make this work:

# Data to be plotted
actual <- c(153.3, 12.5, 52, 23, 11.8, 20.8, 1.9, 26.4, 6, 17, 7.4, 3.5)

# Transform them into a time-series object
ts_actual <- ts(actual, frequency = 12, start = c(2017, 1), end = c(2017, 12))

# Create the labels
labels.chart = seq(as.Date("2017-01-01"), as.Date("2017-12-01"), by = "months")

# My plot
plot(ts_actual, col = "blue", type = "p", ylim = c(-100, 200), xaxt = "n")

# This does not work:
axis(1, labels.chart , format(labels.chart, "%Y-%m"))

# Neither does this:
axis.Date(side = 1, at = labels.chart , format = "%Y-%m")

This is what I get: 在此处输入图片说明

Any hint on what I am missing?

I want to keep my data as a time-series object because this is a part of a time-series analysis. Default x-axis labels are not appropriate:

# Data to be plotted
actual <- c(153.3, 12.5, 52, 23, 11.8, 20.8, 1.9, 26.4, 6, 17, 7.4, 3.5)

# Transform them into a time-series object
ts_actual <- ts(actual, frequency = 12, start = c(2017, 1), end = c(2017, 12))

# Create the labels
labels.chart = seq(as.Date("2017-01-01"), as.Date("2017-12-01"), by = "months")

# My plot
plot(ts_actual, col = "blue", type = "p", ylim = c(-100, 200))

The plot with default labels: 在此处输入图片说明

So, how can I fix this (without using ggplot2 or other unnecessary packages)?

If you specify las=2 on the axis function it will show the labels perpendicular to the x-axis

在此处输入图片说明

Reproducible code

# Data to be plotted
actual <- c(153.3, 12.5, 52, 23, 11.8, 20.8, 1.9, 26.4, 6, 17, 7.4, 3.5)
x <- c(1:12)

# Transform them into a time-series object
ts_actual <- ts(actual, frequency = 12, start = c(2017, 1), end = c(2017, 12))

# Create the labels
labels.chart = seq(as.Date("2017-01-01"), as.Date("2017-12-01"), by = "months")

labels.chart


# My plot
plot(x, ts_actual, col = "blue", type = "p", ylim = c(-100, 200))
axis(1, x, format(labels.chart, "%Y-%m"), las=2)

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