我想在ggplot
中创建按天和月表示时间序列(xts对象(的图表,以比较多年的趋势。
以下是我如何创建数据集:
sales_ <- read_csv("sales.csv")
sales_ <- sales_ %>% mutate(date_ = as_date(date_))
sales_xts <- xts(sales_[!names(sales_) %in% 'date_'], order.by = sales_$date_)
head(sales_xts)
x1 x2
2017-01-02 10 20000.89
2017-01-03 100 90000.53
2017-01-04 120 100000.16
--- -- --
2018-01-06 16 10000.25
2018-01-09 180 100000.68
您可以使用dplyr
和ggplot
:
library(dplyr);library(ggplot2);
sales_xts %>%
gather("key", "value", -date) %>% # gathers your data in the correct long format
# key will contain the names of x1 and x2 (you can change it)
# value will contain the numbers of each
# I supposed you have a column of dates named "date" change that with the correct name
ggplot(aes(x = date, y = value, color = as.factor(key))) +
geom_line(size = 1)