Chris Rucker
Chris Rucker

Reputation: 43

Add multiple geom_line to ggplot

The geom_line CUR_MTH_UNEARN_REV_EUR is plotted correctly as a numeric. My goal is to add a second numeric geom_line (i.e., CUR_MTH_EARN_REV_EUR). Here's the code:

library("ggthemes")
library("gridExtra")
library("grid")

p = ggplot(f, aes(DTE_OF_REPORT_EUR, CUR_MTH_UNEARN_REV_EUR, label=(CUR_MTH_UNEARN_REV_EUR)))
+ geom_point(size=ifelse(f$CUR_MTH_UNEARN_REV_EUR<8.0, 11, 5), color=ifelse(f$CUR_MTH_UNEARN_REV_EUR<8.0, '#CC0000', 'black')) 
+ geom_line(size=2,aes(group=1)) + geom_rangeframe() + theme_wsj() 
+ theme(axis.text.x=element_text(angle=50, size=20, vjust=0.7)) 
+ geom_smooth(aes(group=1), method="loess", colour = "#CC0000", lwd=2) 
+ geom_text(aes(label=CUR_MTH_UNEARN_REV_EUR), hjust=-0.5, vjust=0.5, fontface="bold") 
+ ggtitle("Unearned Revenue by Service Code 'BS', in CSG Months, Jul. 2014-Aug. 2015") 
+ theme(plot.title = element_text(lineheight=.8, face="bold"))

p

Text1 = textGrob("Source: Revenue Assurance and Quality Control", gp=gpar(fontsize=7))
p2 = p + annotation_custom(grob = Text1, ymin = -0.2, ymax = -30)

p2

format(round(f$CUR_MTH_UNEARN_REV_EUR, 2), nsmall = 2)
f$ScoreRounded <- round(f$CUR_MTH_UNEARN_REV_EUR, 1)
f$DTE_OF_REPORT_EUR <- factor(f$DTE_OF_REPORT_EUR, levels=unique(as.character(f$DTE_OF_REPORT_EUR)))

Upvotes: 4

Views: 15747

Answers (1)

Heroka
Heroka

Reputation: 13149

Hope this helps as a start. You can just add things, but you need to have the correct aes.

#data with x and two y-variables
set.seed(123)
f <- data.frame(x=1:10, var1=sample(7:10,10,T),
                var2=sample(5:7,10,T))

#as you want sizing by a measure, make a flag
f$var1_threshold <- f$var1 <9

#example with adding different geoms
#not that it's unnecessary to use my data (f)
#in the call to aes, as everything I need is already 
#inside f
p <- ggplot(f, aes(x=x)) +
  geom_point(aes(y=var1,size=var1_threshold, color=var1_threshold))+
  #colors and size in aes allows for legend generation.
  scale_size_manual(values=c("FALSE"=5,"TRUE"=8)) +
  scale_color_manual(values=c("FALSE"='#CC0000',"TRUE"='black')) +
  geom_line(aes(y=var1),size=1) +
  geom_line(aes(y=var2),size=1) +
  geom_smooth(aes(y=var1), colour="#CC0000") +
  geom_smooth(aes(y=var2), colour="black")

Upvotes: 7

Related Questions