2

I have the following plot of a stock's price in response to time on different days. Currently, using geom_text I'm able to label the points of interest where the Y value deviates from 0 by a significant positive. However, I also wish to label the points where the Y is significantly less than 0. Currently, for geom_Text I have:

geom_text_repel(aes(label=ifelse(percent_change_price_SPY>0.35,as.character(DATE),'')))

I tried adding another condition to the if statement,

geom_text_repel(aes(label=ifelse((percent_change_price_SPY>0.35)|(percent_change_price_SPY<-.35),as.character(DATE),'')))

but it returned the error:

could not find function "|<-"

I also tried breaking it up into two geom_text calls

geom_text_repel(aes(label=ifelse(percent_change_price_SPY>0.35,as.character(DATE),''))) + geom_text_repel(aes(label=ifelse(percent_change_price_SPY<-0.35,as.character(DATE),'')))

but this command does not stop executing. any idea how to get both conditions to display? enter image description here

shoestringfries
  • 279
  • 4
  • 18

1 Answers1

4

A single nested geom_text with two ifelse statements should do the trick, e.g. in this toy data set,

library(data.table)
library(ggplot2)
library(ggrepel)

dat <- data.table(col1=c(rep("A",50), rep("B",50)), col2=rep(1:50,2), col3=runif(100, min=-1, max=1))

ggplot(data=dat, mapping=aes(x=col2, y=col3, color=col1)) +
geom_line() +
geom_text_repel(aes(label=ifelse((col3 > 0.9), col2, ifelse(col3 < -0.9, col2, ""))))

Which in you case would be something along the lines of:

geom_text_repel(aes(label=ifelse((percent_change_price_SPY > 0.35), DATE, ifelse(percent_change_price_SPY < -0.35, DATE, ""))))

Note that the following conditional in your example code would not work as intended:

value<-0.35

as you need a space between the inequality symbol and the negative symbol

caw5cv
  • 701
  • 3
  • 9
  • Yeah, turns out I just needed to use `value<(-.35)` or like you said, a space. This turned out to work `geom_text_repel(aes(label=ifelse((percent_change_price_SPY>0.35)|(percent_change_price_SPY<(-.35)),as.character(DATE),'')))` – shoestringfries Mar 26 '17 at 11:05