#r #plot #time-series
#r #график #временные ряды
Вопрос:
Я хочу отобразить данные из объекта временных рядов и правильно настроить метки, которые отображаются на оси x.
Данные, которые я строю, соответствуют месячным значениям с января 2017 года по декабрь 2017 года.
Я читал другие подобные сообщения на ту же тему здесь, и я перепробовал все, что представлял, но я не могу заставить это работать:
# 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")
Любой намек на то, чего мне не хватает?
Я хочу сохранить свои данные как объект временных рядов, потому что это часть анализа временных рядов. Метки по оси x по умолчанию не подходят:
# 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))
График с метками по умолчанию:
Итак, как я могу это исправить (без использования ggplot2
или других ненужных пакетов)?
Ответ №1:
Если вы укажете las=2
в axis
функции, она покажет метки, перпендикулярные оси x
Воспроизводимый код
# 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)