Vitomir
Vitomir

Reputation: 295

ggplot2 geom_point with color only when y value is different than 0

I am working in R and I have a tibble of three columns:

Date <- structure(c(16636, 16667, 16698, 16728,16759, 16789, 16820, 16851), class = "Date") 
pnl = structure(c(0, 0, 5, 0, 10, 2.2, 0, 0))          
df <- cbind(Date,pnl) %>% as_tibble()

I want to plot with ggplot:

I tried the following:

ggplot(data = df) + 
    geom_line(aes(x = Date, y = cumsum(pnl)), color = "blue") +
    geom_point(aes(x = Date, y = ifelse(pnl != 0, cumsum(pnl),0), color = ifelse(pnl != 0,1,0)))

But it gives me an error. Any idea how to address this? Many thanks.

Upvotes: 0

Views: 418

Answers (1)

Duck
Duck

Reputation: 39613

Try creating a variable for the color like this:

library(tidyverse)
#Data
Date <- structure(c(16636, 16667, 16698, 16728,16759, 16789, 16820, 16851), class = "Date") 
pnl = structure(c(0, 0, 5, 0, 10, 2.2, 0, 0))          
df <- data.frame(Date,pnl)
#Color
df$Color=ifelse(df$pnl!= 0,1,0)
#Plot
ggplot(data = df) + 
  geom_line(aes(x = Date, y = cumsum(pnl)), color = "blue") +
  geom_point(aes(x = Date, y = ifelse(pnl != 0, cumsum(pnl),0),color=factor(Color)))+
  scale_x_date(date_labels = '%Y-%m-%d')

Output:

enter image description here

Or more customized:

#Plot 2
ggplot(data = df) + 
  geom_line(aes(x = Date, y = cumsum(pnl)), color = "blue") +
  geom_point(aes(x = Date, y = ifelse(pnl != 0, cumsum(pnl),0),color=factor(Color)))+
  scale_x_date(date_labels = '%Y-%m-%d')+
  scale_color_manual('Value',values=c('red','blue'))

Output:

enter image description here

For transparent color:

#Plot 3
ggplot(data = df) + 
  geom_line(aes(x = Date, y = cumsum(pnl)), color = "blue") +
  geom_point(aes(x = Date, y = ifelse(pnl != 0, cumsum(pnl),0),color=factor(Color)))+
  scale_x_date(date_labels = '%Y-%m-%d')+
  scale_color_manual('Value',values=c('transparent','blue'))+
  theme(legend.position = 'none')

Output:

enter image description here

Upvotes: 2

Related Questions