2017-06-16 22 views
-1

我有這樣的數據:選擇特定的列數據的geom點

Date    ID Value 
10-Apr-17 12:02:30 A 4.107919756 
10-Apr-17 12:02:31 A 4.107539119 
10-Apr-17 12:02:32 A 5.503949115 
10-Apr-17 12:02:33 B 5.842728032 
10-Apr-17 12:02:34 B 8.516053634 
10-Apr-17 12:02:35 B 1.515112486 
10-Apr-17 12:02:36 B 5.224667007 

我想繪製geom_point僅使用列ID ==「A」。

library(ggplot2) 
library(lubridate) 
library(magrittr) 

thedata <- read.csv("~/Downloads/Vel.csv", header = TRUE) 

thedata$newDate <- dmy_hms(thedata$Date) 
ggplot(thedata, aes(newDate, Value)) + 
    geom_point(thedata=thedata$ID %>% filter(thedata$ID == "A")) 

但它繪製了所有點(A和B ID)。

而且它使用ggplot時給我

"Warning: Ignoring unknown parameters: thedata"

UPDATE

使用:

thedata <- read.csv("~/Downloads/Vel.csv", header = TRUE) 
thedata <- as.data.frame(thedata) 
thedata$newDate <- dmy_hms(thedata$Date) 
ggplot(thedata, aes(newDate, Value)) + 
    geom_point(data=thedata$ID %>% filter(thedata$ID == "A")) 

因此,使用數據作爲數據幀,並使用geom_point(data=thedata$ID %>%代替geom_point(thedata=thedata$ID %>%作爲@aosmith指出,

結果:

Error: ggplot2 doesn't know how to deal with data of class ts

+0

的說法是'data'不是'thed ata'。您需要將data.frame傳遞給該參數;在你目前的代碼中,它看起來像你正在使用矢量。 – aosmith

+0

@aosmith:是的,我錯過了'數據'的事情。我更新了,但仍然有錯誤。 – George

+0

你是否試圖使用dplyr中的'filter'或stats中的'filter'?如果前者是'thedata%>%filter(ID ==「A」)' – aosmith

回答

2

我認爲這是你的方式ð做到這一點:

ggplot(thedata %>% dplyr::filter(ID == "A"), aes(newDate, Value)) + 
geom_point() 

的一點是,你可以在geom時指定一個在ggplot沒有指定新的數據框()。我想你也可以做這樣的事情:

ggplot() + 
geom_point(data = thedata %>% dplyr::filter(ID == "A"), aes(newDate, Value)) 

編輯:

我更新了第二個代碼塊,所以應該現在的工作。

關於filter()函數,你不需要在你的情況下管道thedata。這項工作也很好,並且更容易閱讀:geom_point(data = filter(thedata, ID == "A"), aes(newDate, Value))

而且,這只是我的意見,但我想它會更有趣,爲您的ID繪製整個數據和顏色,就像這樣:

ggplot() + 
geom_point(data = thedata, aes(newDate, Value, colour = ID)) 

要完成上一個數據幀餵養ggplot()的問題,注意,如果你沒有,你可以用mtcars數據集指定不同的data所有的geom,如本例:

ggplot() + 
    geom_point(data = mtcars, aes(mpg, disp, colour = cyl)) + 
    geom_point(data = filter(mtcars, cyl == 6), aes(qsec, drat)) 
+0

你的最後一個例子不能像寫入的那樣工作。您需要明確寫出'data'參數或傳遞數據集作爲函數中的第二個參數。 'data'參數在geom圖層中不是*,而是在'ggplot'中。 – aosmith

+0

好的,謝謝你的幫助。(upv)。我試圖將數據加載到ggplot()中,以便讓它們已經存在,因爲除了geom_point之外,還可能需要添加其他內容。所以,我不想再寫數據(newDate,Value)。這就是爲什麼我想'ggplot(thedata,aes(newDate,Value))+ geom_point(...)',但我不想要再次使用'aes(newDat,Value)'。 – George