我正在尝试在ggplot中创建每月时间序列以进行时间序列分析。这是我的数据:
rdata1 <- read_table2("date sales_revenue_incl_credit 2017-07 56,037.46 2017-08 38333.9 2017-09 48716.92 2017-10 65447.67 2017-11 134752.57 2017-12 116477.39 2018-01 78167.25 2018-02 75991.44 2018-03 42520.93 2018-04 70489.92 2018-05 121063.35 2018-06 76308.47 2018-07 118085.7 2018-08 96153.38 2018-09 82827.1 2018-10 109288.83 2018-11 145774.52 2018-12 141572.77 2019-01 123055.83 2019-02 104232.24 2019-03 435086.33 2019-04 74304.96 2019-05 117237.82 2019-06 82013.47 2019-07 99382.67 2019-08 138455.2 2019-09 97301.99 2019-10 137206.09 2019-11 109862.44 2019-12 118150.96 2020-01 140717.9 2020-02 127622.3 2020-03 134126.09")
我现在使用以下代码更改日期的类别,然后使用date_labels和date_breaks轻松绘制带有中断和标签的图形。
rdata1 %>% mutate(date = ymd(date)) %>% ggplot(aes(date, sales_revenue_incl_credit)) + geom_line() + scale_x_date(date_labels = "%b %Y", date_breaks = "1 month")+ theme_bw()+ theme(axis.text.x = element_text(angle = 90, vjust=0.5), panel.grid.minor = element_blank())
我收到以下错误:
seq.int(r1 $ mon,12 *(to0 $ year-r1 $ year)+ to0 $ mon,by)中的错误: “ from”必须为有限数字
答案 0 :(得分:1)
将所有这些问题放在一起,我进行了一些数据准备工作以获得所需的输出。首先,如注释中所述,我将每个月的第一天附加到每个“年-月”,以便可以在R中使用适当的日期变量。其次,我在{{上使用了column_to_rownames()
1}}列。我在年份名称后附加了年份,因为不允许重复(非唯一)行名称。我应该警告您不要使用行标签。引用文档(参见month_year
):
虽然小标题可以具有行名(例如,从常规数据帧转换时的行名),但在使用[运算符进行子设置时,会将其删除。尝试为小标题分配非NULL行名时,将出现警告。通常,最好避免使用行名,因为它们基本上是字符列,其语义与其他列不同。
您可以使用不同的命名约定来操作下面的行名。只要确保标签是唯一的!请参见下面的R代码:
?tibble::rownames_to_column
答案 1 :(得分:0)
@Tom答案的一个更简单的版本是使用tsibble对象和feasts
包:
# Loading the required libraries
library(tibble)
library(dplyr)
library(ggplot2)
library(lubridate)
library(tsibble)
library(feasts)
# Data preparation
df <- tribble(
~date, ~sales_revenue_incl_credit,
"2017-07", 56037.46,
"2017-08", 38333.9,
"2017-09", 48716.92,
"2017-10", 65447.67,
"2017-11", 134752.57,
"2017-12", 116477.39,
"2018-01", 78167.25,
"2018-02", 75991.44,
"2018-03", 42520.93,
"2018-04", 70489.92,
"2018-05", 121063.35,
"2018-06", 76308.47,
"2018-07", 118085.7,
"2018-08", 96153.38,
"2018-09", 82827.1,
"2018-10", 109288.83,
"2018-11", 145774.52,
"2018-12", 141572.77,
"2019-01", 123055.83,
"2019-02", 104232.24,
"2019-03", 435086.33,
"2019-04", 74304.96,
"2019-05", 117237.82,
"2019-06", 82013.47,
"2019-07", 99382.67,
"2019-08", 138455.2,
"2019-09", 97301.99,
"2019-10", 137206.09,
"2019-11", 109862.44,
"2019-12", 118150.96,
"2020-01", 140717.9,
"2020-02", 127622.3,
"2020-03", 134126.09
) %>%
mutate(date = yearmonth(date)) %>%
as_tsibble(index=date)
# Reproducing your plot
df %>% autoplot(sales_revenue_incl_credit) +
scale_x_yearmonth(breaks=seq(1e3)) +
theme_bw() +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5),
panel.grid.minor = element_blank())
由reprex package(v0.3.0)于2020-06-19创建