2011-08-30 17 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から最後まで破線をしたいです。私はちょうど2つの別々のラインセグメントを行うか、または私は望む結果を得るために使用できる別のコマンドがありますか?

答えて

20

ggplotの哲学は単純です。プロットの各要素は異なるレイヤーにある必要があります。したがって、異なる行タイプの2つの線分を取得するには、2つの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

関連する問題