Create a partial dashed line in ggplot2

前端 未结 1 1133
醉梦人生
醉梦人生 2021-02-04 06:37

I\'m creating a plot in R and need to create a line where some of the values are projections. The projections are represented as a dashed line. Here\'s the code:



        
相关标签:
1条回答
  • 2021-02-04 06:59

    The ggplot philosopy is simple. Each element of a plot needs to be on a different layer. Thus to get two line segments in different line types, you need two geom_segment statements.

    I illustrate the same principle with geom_bar in different colours for your different periods.

    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

    0 讨论(0)
提交回复
热议问题