2017-04-19 129 views
0

这里是我的例子,用ggplot绘制多条线。它产生以下错误R中ggplot的多条线

library(ggplot2) 
test_df <-data.frame(dates= c('12/12/2011', '12/12/2011', '12/13/2011','12/13/2011'), 
        cat = c('a','b','a','b'), value = c(5,6,8,9)) 

ggplot(data= test_df, aes(x=dates, y = value, colour = cat)) + geom_line() 

错误:

geom_path: Each group consists of only one observation. Do you 
need to adjust the group aesthetic? 

我缺少什么?我用下面的例子:Stackoverflow

+2

我想ggplot会提醒你,它可能会误解你,因为y你给它4个离散的“桶”,每个桶只有一个元素,你想为每个桶绘制一条线,这是没有意义的。你可以通过告诉ggplot由猫分组(通过在'aes'中添加'group = cat',或者通过提供一个连续的x轴而不是离散的一个(例如'x = lubridate :: mdy(dates)')来修复它在'aes'里面)。 – lukeA

回答

1

错误出现如datestest_df是分类变量

str(test_df) 

'data.frame': 4 obs. of 3 variables: 
$ dates: Factor w/ 2 levels "12/12/2011","12/13/2011": 1 1 2 2 
$ cat : Factor w/ 2 levels "a","b": 1 2 1 2 
$ value: num 5 6 8 9 

这可以通过ggplot命令内改变类的dates容易地修正:

ggplot(test_df, aes(x=as.Date(dates, format="%m/%d/%y"), y=value, colour=cat)) + 
    geom_line() 

enter image description here