我有一個包含 4 列的資料框。這包括 week_no(一年中的一周)、日期(該周的星期五日期)、年份、銷售額。
我想繪制一個折線圖,按周顯示冬季期間的銷售額。冬季從第 50 周到第 4 周。每個冬季都應該有自己的線條和顏色。
示例資料框代碼
library(ggplot2)
df <- data.frame(
week_no = c("50","51","52","1","2","3","4","50","51","52","1","2","3","4"),
date = c("2018-12-14", "2018-12-21", "2018-12-28", "2019-01-04", "2019-01-11", "2019-01-18", "2019-01-25", "2019-12-13", "2019-12-20", "2019-12-27", "2020-01-03", "2020-01-10", "2020-01-17", "2020-01-24"),
year = c("2018", "2018", "2018", "2019", "2019", "2019", "2019", "2019", "2019", "2019", "2020", "2020", "2020", "2020"),
sales = c(546,873,532,424,235,321,531,865,869,458,234,654,345,984))
示例資料框
| week_no | 日期 | 年 | 銷售量 |
|---|---|---|---|
| 50 | 2018-12-14 | 2018 | 546 |
| 51 | 2018-12-21 | 2018 | 873 |
| 52 | 2018-12-28 | 2018 | 532 |
| 1 | 2019-01-04 | 2019 | 424 |
| 2 | 2019-01-11 | 2019 | 235 |
| 3 | 2019-01-18 | 2019 | 321 |
| 4 | 2019-01-25 | 2019 | 531 |
| 50 | 2019-12-13 | 2019 | 865 |
| 51 | 2019-12-20 | 2019 | 869 |
| 52 | 2019-12-27 | 2019 | 458 |
| 1 | 2020-01-03 | 2020 | 234 |
| 2 | 2020-01-10 | 2020 | 654 |
| 3 | 2020-01-17 | 2020 | 345 |
| 4 | 2020-01-24 | 2020 | 984 |
我已經嘗試了下面的代碼,它給出的結果接近我需要的結果,但年份不匹配,并且周順序連續運行 1-52。
我希望 x 軸按 50、51、52、1、2、3 排序,并且每一行按日期順序而不是年份類似地顯示資料。
代碼
winter_line_plot <- ggplot(df, aes(x = week_no, y = sales))
geom_line(aes(color = year))
我嘗試使用 x 軸的日期,但我的結果顯示了一條連續的線,而不是不同冬季的不同顏色/線。
uj5u.com熱心網友回復:
您需要添加年份作為美學。保持周離散,并添加比例限制。為了獲得季節,您在評論中為每個季節創建分組變數的想法肯定是最直接的。
library(tidyverse)
df <- data.frame(
week_no = c("50","51","52","1","2","3","4","50","51","52","1","2","3","4"),
date = c("2018-12-14", "2018-12-21", "2018-12-28", "2018-01-04", "2018-01-11", "2018-01-18", "2018-01-25", "2019-12-13", "2019-12-20", "2019-12-27", "2020-01-03", "2020-01-10", "2020-01-17", "2020-01-24"),
year = c("2018", "2018", "2018", "2019", "2019", "2019", "2019", "2019", "2019", "2019", "2020", "2020", "2020", "2020"),
sales = c(546,873,532,424,235,321,531,865,869,458,234,654,345,984))
## if your data is indeed very regular and contains always one and no more than one row per week,
## then you can easily create the groups with rep
## (make sure the data frame is sorted by year and week)
df %>%
arrange(year, week_no) %>%
mutate(season = rep(c("winter_1819"," winter_1920"), each = 7)) %>%
ggplot()
## week is discrete, so you need to specify group
geom_line(aes(week_no, sales, color = season, group = season))
## set axis breaks
scale_x_discrete(limits = as.character(c(50:52, 1:4) ))

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/491029.html
