2015-11-05 45 views
1

我一直在試圖標籤添加到我的散點圖的點,但我不斷收到一個問題的時候:錯誤解析(文= X),包括非重疊標籤在GGPLOT2

Error in parse(text = x) : <text>:1:1: unexpected '$' 
1: $ 
    ^

我已經看了在與direct.label包相關的帖子的大部分,但我似乎無法發現我做錯了什麼。

這裏的問題的再現:

library(ggplot2) 
library(directlabels) 

data <- data.frame(X= c("A","B","C","D","X","Y","S","P","L","W"), Y=rnorm(10), Z=rnorm(10)) 
data$X <- as.character(data$X) 
graph <- ggplot(data, aes(data$Y,data$Z)) 
t2<-theme(        
     axis.title.x = element_text(face="bold", color="black", size=15), 
     axis.title.y = element_text(face="bold", color="black", size=15), 
     plot.title = element_text(face="bold", color = "black", size=12), 
     axis.text.x = element_text(size=15), 
     axis.text.y = element_text(size=15) 
) 
graph <- graph + geom_point(aes(colour=data$X), size=3) + geom_smooth(method="lm", se=F, size=0.5) + 
     xlab("Y") + ylab("Z") + 
     geom_vline(xintercept=mean(data$Y), color="red", size=1, linetype=2) + theme_bw() + t2 + 
     geom_text(x=740,y=105, label="Avg", size=4.5); graph 

direct.label.ggplot(graph) 
+1

不要使用美元符號的符號'aes'內。您可以在'ggplot'中定義圖表中使用的數據集,因此可以(也應該!)直接引用每個變量。 – aosmith

回答

0

刪除了data$Y等(根據AOSMITH的建議),和定義meanYggplot調用之前。

library(ggplot2) 
library(directlabels) 

data <- data.frame(X= c("A","B","C","D","X","Y","S","P","L","W"), 
         Y=rnorm(10), Z=rnorm(10)) 
data$X <- as.character(data$X) 
meanY <- mean(data$Y) 

graph <- ggplot(data, aes(Y,Z)) 
t2<-theme(        
    axis.title.x = element_text(face="bold", color="black", size=15), 
    axis.title.y = element_text(face="bold", color="black", size=15), 
    plot.title = element_text(face="bold", color = "black", size=12), 
    axis.text.x = element_text(size=15), 
    axis.text.y = element_text(size=15) 
) 
graph <- graph + geom_point(aes(colour=X), size=3) + 
    geom_smooth(method="lm", se=F, size=0.5) + 
    xlab("Y") + ylab("Z") + 
    geom_vline(xintercept=meanY, color="red", size=1, linetype=2) + 
    theme_bw() + t2 + 
    geom_text(x=740,y=105, label="Avg", size=4.5); 

print(graph) 

direct.label.ggplot(graph) 

此息率與沒有錯誤或警告: enter image description here

+0

問題是美學映射中的美元符號表示法 - 該繪圖與'geom_vline'中的mean(data $ y)'一起工作,因爲它將x截距設置爲一個值,而不是映射到美學。 – aosmith