首页 > 解决方案 > Creating line graph in ggplot2

问题描述

So I have the following data:

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"))

and I thought making this a line graph with two lines (indicated by Reportable) would be as simple as the following but this doesn't seem to be the case...

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

标签: rggplot2linechart

解决方案


Try this:

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

Output:

enter image description here


推荐阅读