问题描述
我正在R中工作,并且有三列标题:
-
Date
,日期列 -
pnl
,一个连续的double列。但是,此列主要是= 0,很少是!= 0。
Date <- structure(c(16636,16667,16698,16728,16759,16789,16820,16851),class = "Date")
pnl = structure(c(0,5,10,2.2,0))
df <- cbind(Date,pnl) %>% as_tibble()
我想用ggplot进行绘图:
我尝试了以下操作:
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)))
解决方法
尝试为这种颜色创建变量:
library(tidyverse)
#Data
Date <- structure(c(16636,16667,16698,16728,16759,16789,16820,16851),class = "Date")
pnl = structure(c(0,5,10,2.2,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')
输出:
或更个性化:
#Plot 2
ggplot(data = df) +
geom_line(aes(x = Date,color=factor(Color)))+
scale_x_date(date_labels = '%Y-%m-%d')+
scale_color_manual('Value',values=c('red','blue'))
输出:
对于透明颜色:
#Plot 3
ggplot(data = df) +
geom_line(aes(x = Date,values=c('transparent','blue'))+
theme(legend.position = 'none')
输出: