2017-04-19 125 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