2013-04-08 33 views
3

我有一个分布文件看起来像这样:GGPLOT - 如何根据预定义的标签区分线,并添加文本在x轴

Function Freq 
foo 1117 
... 
qux 1992 
.. 
bar 4158 
.. 

完整的数据可以下载here

我想要做的是创造密度的情节,有以下:

  1. 将一个geom_vline在x = 800,也表明在曲线中值800。
  2. 对于分布“酒吧”使用不同厚度的虚线,而不是正常的实线。

这样它创建这样的图形。 enter image description here

但我坚持下面的代码。什么是最好的方式来做到这一点?

library(ggplot2) 
library(RColorBrewer) 

pal <- c(brewer.pal(8,"Dark2"),brewer.pal(12,"Paired")); 
dat<-read.table("http://dpaste.com/1051018/plain/",header=TRUE); 
dat.sub <- data.frame(dat$Function,dat$Freq) 


ggplot(dat.sub,aes(dat.Freq,color=dat.Function),shape=dat.Function)+ 
stat_density(geom="path",position="identity",size=0.5)+ 
theme(legend.position="none")+ 
scale_color_manual(values=pal)+ 
geom_vline(xintercept=800,colour="red",linetype="longdash") 
+1

1为图纸。 – Eduardo 2014-11-07 09:39:16

回答

6

为了改变线的类型就应该把linetype=dat.Functionaes()内,然后使用scale_linetype_manual()改变线的类型,类似与线大小 - 放size=dat.Function内部aes(),然后使用scale_size_manual()改变线宽度(应删除size=0.5表格stat_density())要标记垂直线的位置,一种可能性是用scale_x_continuous()更改x轴上的中断,或者在annotate()的内部添加一些文字。

ggplot(dat.sub,aes(dat.Freq,color=dat.Function, 
      linetype=dat.Function,size=dat.Function))+ 
    stat_density(geom="path",position="identity")+ 
    scale_color_manual(values=pal)+ 
    geom_vline(xintercept=800,colour="red",linetype="longdash")+ 
    scale_linetype_manual(values=c(2,1,1))+ 
    scale_size_manual(values=c(2,0.8,0.8))+ 
    scale_x_continuous(breaks=c(0,800,2500,5000,7500,10000))+ 
    annotate("text",label="x=800",x=800,y=-Inf,hjust=0,vjust=1) 

enter image description here

如果你想放置文本x=800轴的一种方法是使用的网格物体下,另一种可能是与scale_x_continuous()theme()玩。首先,在scale_x_continuos()中设置了breaks=labels=,并且对于位置800使用x=800。现在x轴下有6个数字。使用theme()axis.text.x=您可以更改文本的功能。如果给值的矢量用于改变则每个轴文本将具有单独的功能的元件(I设置为2元件不同的特征(文本X = 800))

ggplot(dat.sub,aes(dat.Freq,color=dat.Function, 
       linetype=dat.Function,size=dat.Function))+ 
    stat_density(geom="path",position="identity")+ 
    scale_color_manual(values=pal)+ 
    geom_vline(xintercept=800,colour="red",linetype="longdash")+ 
    scale_linetype_manual(values=c(2,1,1))+ 
    scale_size_manual(values=c(2,0.8,0.8))+ 
    scale_x_continuous(breaks=c(0,800,2500,5000,7500,10000), 
        labels=c(0,"x=800",2500,5000,7500,10000))+ 
    theme(axis.text.x= 
     element_text(color=c("grey35","red","grey35","grey35","grey35"), 
        size=rel(c(1,1.2,1,1,1,1)), 
        face=c("plain","bold","plain","plain","plain","plain"))) 

enter image description here

+1

更新了我的解决方案以更改线宽。 – 2013-04-08 13:32:36