如何在带有离散x轴的ggplot中制作折线图?

How to make a line graph in ggplot with discrete x-axis?

所以我有一个table如下:

data <- structure(list(Variable = c("Content", "Content", "Content", 
"Content", "Content", "Content"), content_type = c("LIVE", 
"LIVE", "LIVE", "VOD", "VOD", "VOD"), CURRENT_STATUS = c("ACTIVE", 
"CANCELLED", "EXPIRED", "ACTIVE", "CANCELLED", "EXPIRED"), `1 Day` = c(0.768763, 0.734808, 0.714794, 1.200606, 0.766533, 
0.765004), `7 Day` = c(1.181393, 0.989723, 1.035509, 
3.793286, 1.734361, 2.112217), `14 Day` = c(1.431612, 
1.123995, 1.206466, 5.428656, 2.226542, 2.868766), 
    `21 Day` = c(1.609405, 1.189455, 1.313989, 6.671368, 2.485925, 
    3.381902), `28 Day` = c(1.785089, 1.237489, 1.415171, 
    7.717914, 2.678954, 3.795692), `35 Day` = c(1.945274, 
    1.274576, 1.488107, 8.644254, 2.815237, 4.101302), `42 Day` = c(2.095211, 1.306524, 1.540499, 9.465924, 2.932306, 
    4.320128), `49 Day` = c(2.286882, 1.344057, 1.616501, 
    10.245316, 3.04714, 4.532644), `56 Day` = c(2.426061, 
    1.369303, 1.666257, 10.937274, 3.169794, 4.709551), `90 Day` = c(2.974361, 1.435433, 1.812601, 13.656243, 
    3.419348, 5.263874)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

所以每一列的数值数据如下:

1 Day
7 Day
14 Day
21 Day
...
90 Day

所以我希望每一天都是 x 轴上的一个刻度,y 值是值,每个 current_status 和两个 table 总共 3 行,每个 content_type.

我希望它看起来像这样:

ggplot(df, aes(x = day, y = count)) + 
  geom_line(aes(color = CURRENT_STATUS, linetype = CURRENT_STATUS))+
facet_wrap(~content_type)

但我不确定如何将天数(作为变量名的字符串)表示为它们在 x 轴上的实际数值天值(因此,被计数的 y 将是 table..

所以基本上,我需要整理这个 table 才能使具有上述规格的折线图有意义。

我认为您只需要旋转数据、对日期进行排序并在美学上分配分组即可:

library(tidyverse)

data_long <- data %>%
  pivot_longer(cols = ends_with("Day"),
           names_to = "day",
           values_to = "count") %>%
  mutate(day = as_factor(day)) 

  ggplot(data = data_long, aes(x = day, y = count, group = CURRENT_STATUS)) + 
  geom_line(aes(color = CURRENT_STATUS, linetype = CURRENT_STATUS)) +
  facet_wrap(~content_type)