1

我一直在尝试为散点图中的点添加标签,但我一直遇到问题:

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)
4

1 回答 1

0

删除data$Y等(根据 aosmith 的建议),并在调用meanY之前定义。ggplot

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)

产生这个没有错误或警告: 在此处输入图像描述

于 2015-11-06T12:36:15.757 回答