在 ggplot2 中创建折线图

Creating line graph in ggplot2

所以我有以下数据:

df <- structure(list(m_y = structure(c(1L, 13L, 10L, 11L, 12L, 2L, 
14L, 3L, 15L, 4L, 16L, 5L, 17L, 6L, 18L, 7L, 8L, 9L, 1L, 13L, 
10L, 11L, 12L, 2L, 14L, 3L, 15L, 4L, 16L, 5L, 17L, 6L, 18L, 7L, 
8L, 9L), .Label = c("1-2018", "2-2018", "3-2018", "4-2018", "5-2018", 
"6-2018", "7-2018", "8-2018", "9-2018", "10-2018", "11-2018", 
"12-2018", "1-2019", "2-2019", "3-2019", "4-2019", "5-2019", 
"6-2019"), class = "factor"), count = c(29L, 32L, 32L, 22L, 26L, 
34L, 29L, 46L, 31L, 40L, 26L, 35L, 28L, 47L, 37L, 44L, 36L, 21L, 
80L, 84L, 59L, 51L, 48L, 60L, 63L, 67L, 63L, 52L, 58L, 65L, 50L, 
67L, 61L, 67L, 70L, 65L), Reportable = c("Non", 
"Non", "Non", "Non", 
"Non", "Non", "Non", 
"Non", "Non", "Non", 
"Non", "Non", "Non", 
"Non", "Non", "Non", 
"Non", "Non", "Report", 
"Report", "Report", "Report", 
"Report", "Report", "Report", 
"Report", "Report", "Report", 
"Report", "Report", "Report", 
"Report", "Report", "Report", 
"Report", "Report")), row.names = c(NA, 
-36L), groups = structure(list(m_y = structure(1:18, .Label = c("1-2018", 
"2-2018", "3-2018", "4-2018", "5-2018", "6-2018", "7-2018", "8-2018", 
"9-2018", "10-2018", "11-2018", "12-2018", "1-2019", "2-2019", 
"3-2019", "4-2019", "5-2019", "6-2019"), class = "factor"), .rows = structure(list(
    c(1L, 19L), c(6L, 24L), c(8L, 26L), c(10L, 28L), c(12L, 30L
    ), c(14L, 32L), c(16L, 34L), c(17L, 35L), c(18L, 36L), c(3L, 
    21L), c(4L, 22L), c(5L, 23L), c(2L, 20L), c(7L, 25L), c(9L, 
    27L), c(11L, 29L), c(13L, 31L), c(15L, 33L)), ptype = integer(0), class = c("vctrs_list_of", 
"vctrs_vctr", "list"))), row.names = c(NA, 18L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

我认为用两条线(由 Reportable 表示)制作一个折线图会像下面这样简单,但事实似乎并非如此...

ggplot(df, aes(y=count, x=as.factor(m_y), color=Reportable)) +
  geom_line()

试试这个:

ggplot(df, aes(y=count, x=factor(m_y), color=Reportable,group=Reportable)) +
  geom_line()

输出:

ggplot(df, aes(y=count, x=as.factor(m_y), group=Reportable, color=Reportable)) +
  geom_line()

但是 Non-Reportable 只有一个观察值,因此不会出现该行。

您可以使用点和线:

ggplot(df, aes(y=count, x=as.factor(m_y), group=Reportable, color=Reportable)) +
  geom_line() +
  geom_point()