在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,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,22L,26L,34L,29L,46L,31L,40L,35L,28L,47L,37L,44L,36L,21L,80L,84L,59L,51L,48L,60L,63L,67L,52L,58L,65L,50L,61L,70L,65L),Reportable = c("Non","Non","Report","Report")),row.names = c(NA,-36L),groups = structure(list(m_y = structure(1:18,.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"))),18L),class = c("tbl_df","tbl","data.frame"),.drop = TRUE),class = c("grouped_df","tbl_df","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()

输出:

enter image description here

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

但是对于Non-Reportable只有一个观察结果,因此不会出现任何一行。

您可以使用点和线:

ggplot(df,color=Reportable)) +
  geom_line() +
  geom_point()