Reputation: 295
I am working in R and I have a tibble of three columns:
Date
, a column of datespnl
, a continuous column of double. Nevertheless, this column is mostly = 0 and few times != 0.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:
Date, on the x axis
cumsum(pnl)
, on the y axis as a line plotcumsum(pnl)
line plot whenever the pnl
value is different than 0
.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
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:
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:
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:
Upvotes: 2