1

I've been trying to add labels to the dots in my scatterplot but I keep getting a problem:

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

I've looked at most of the posts related to the direct.label package but I can't seem to spot what I'm doing wrong.

Here's a reproduction of the problem:

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)
cimentadaj
  • 1,414
  • 10
  • 23
  • 1
    Don't use dollar sign notation inside of `aes`. You define the dataset used in the graph within `ggplot` and so can (and should!) refer to each variable directly. – aosmith Nov 05 '15 at 22:44

1 Answers1

0

Removed the data$Y, etc. (as per aosmith's suggestion), and defined meanY before the ggplot calls.

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)

Yields this with no errors or warnings: enter image description here

Mike Wise
  • 22,131
  • 8
  • 81
  • 104
  • The problem is the dollar sign notation in the aesthetics mapping - the plot works with `mean(data$y)` in `geom_vline` because that's setting the x intercept to a value and not mapping to an aesthetic. – aosmith Nov 06 '15 at 15:43