首页 文章

在ggplot2中创建部分虚线

提问于
浏览
12

我在R中创建一个图,需要创建一条线,其中一些值是投影 . 投影用虚线表示 . 这是代码:

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年到结束的虚线 . 我只是做两个单独的线段,或者是否有一个单独的命令可以用来获得所需的结果 .

1 回答

  • 25

    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

相关问题