2011-08-30 213 views
10

我在R中創建了一個圖形,並且需要創建一個行,其中一些值是預測。投影以虛線表示。下面的代碼:在ggplot2中創建部分虛線

df = data.frame(date=c(rep(2008:2013, by=1)), 
       value=c(303,407,538,696,881,1094)) 


ggplot(df, aes(date, value, width=0.64)) + 
     geom_bar(stat = "identity", fill="#336699", colour="black") + 
     ylim(c(0,1400)) + opts(title="U.S. Smartphone Users") + 
     opts(axis.text.y=theme_text(family="sans", face="bold")) + 
     opts(axis.text.x=theme_text(family="sans", face="bold")) + 
     opts(plot.title = theme_text(size=14, face="bold")) + 
     xlab("Year") + ylab("Users (in millions)") +   
     opts(axis.title.x=theme_text(family="sans")) + 
     opts(axis.title.y=theme_text(family="sans", angle=90)) + 
     geom_segment(aes(x=2007.6, xend=2013, y=550, yend=1350), arrow=arrow(length=unit(0.4,"cm"))) 

所以我創建延伸從2008年到2013年。不過,我想2008至2011年的實線一條線,以及從2011年的虛線到最後。我只是做兩個單獨的線段,還是有一個單獨的命令,我可以用來獲得所需的結果。

回答

20

這個ggplot哲學很簡單。繪圖中的每個元素都需要位於不同的圖層上。因此,要獲取不同線型的兩條線段,您需要兩條geom_segment語句。

我用不同顏色的geom_bar來說明你的不同時期的相同原理。

ggplot(df[df$date<=2011, ], aes(date, value, width=0.64)) + 
    geom_bar(stat = "identity", fill="#336699", colour="black") + 
    geom_bar(data=df[df$date>2011, ], aes(date, value), 
     stat = "identity", fill="#336699", colour="black", alpha=0.5) + 
    ylim(c(0,1400)) + opts(title="U.S. Smartphone Users") + 
    opts(
     axis.text.y=theme_text(family="sans", face="bold"), 
     axis.text.x=theme_text(family="sans", face="bold"), 
     plot.title = theme_text(size=14, face="bold"), 
     axis.title.x=theme_text(family="sans"), 
     axis.title.y=theme_text(family="sans", angle=90) 
    ) + 
    xlab("Year") + ylab("Users (in millions)") +   
    geom_segment(aes(x=2007.6, xend=2011, y=550, yend=1050), linetype=1) + 
    geom_segment(aes(x=2011, xend=2013, y=1050, yend=1350), 
     arrow=arrow(length=unit(0.4,"cm")), linetype=2) 

enter image description here