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

标签 r ggplot2 tidyverse linegraph

所以我有一个表格如下:

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 总共 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 将是表中的所有值......

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

最佳答案

我认为您只需要调整数据,对日期进行排序,并在美学中分配分组:

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)

enter image description here

关于r - 如何在ggplot中制作具有离散x轴的折线图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71012981/

相关文章:

r - 当在 data.table 中链接时,autoplot 将空白图保存到 png 设备

r - ggplot2 在 aes 中使用 toupper

r - tidyverse 解决方案,用于将多个列重新编码为新列,其中列名后缀增加一

r - tidytext——如何做共性和对比词云

将 R 崩溃报告为错误

r - ggplot中代码布局的外化

r - 不同 facet_grids 的不同颜色

r - R数据帧中基于静态函数的逻辑函数

r - 数据框中的条件计数

r - 将参数传递给 data.table 聚合函数