2013-08-16 134 views
0

我正在使用ggplot2創建一個點圖。我的數據基本上是三列x_axis,y_axis和z_axis的形式,x_axis和y_axis一起表示一對,z_axis表示對數。ggplot2避免被繪製點

因此,我正在繪製x_axis與y_axis並使用z_axis爲點着色。 在某些情況下,我想跳過繪製一個特定的計數,例如:1的計數發生多次,有時我想跳過繪製1,但圖例應顯示1.以下是我的代碼:

> new<-read.table("PB1_combo.txt", header=T, sep="\t") 
    > bp <-ggplot(data=new, aes(x_axis,y_axis, colour=factor(z_axis)), size=z_axis) +         
    geom_point(size=5) 
    > bp + ggtitle("PB1-PB1") 
    > last_plot()+ scale_colour_discrete(name="Counts") 
    > last_plot()+ theme_bw() 


    Sample data from PB1_combo.txt 
    x_axis y_axis z_axis 
    14  576  2 
    394  652  2 
    759  762  2 
    473  762  2 
    65  763  3 
    114  390  2 
    762  763  4 
    758  762  2 
    388  616  2 
    217  750  2 
    65  762  2 
    473  763  2 
    743  759  2 
    65  213  2 
    743  762  2 
+0

請給我們樣本數據,說明你的問題。我們沒有'PB1_combo.txt'。做到這一點的最好方法是模擬某些內容併發布代碼或發佈'dput(head(new))'。這兩種方法都在[這裏]描述(http://stackoverflow.com/q/5963269/903061)。 – Gregor

+0

如果您不清楚如何使用數據編寫問題,請閱讀[this](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – SlowLearner

回答

1

首先,您應該創建一個因子z_axis。這樣,即使不是所有可能的值都存在,R也會意識到它們。

new$Count <- factor(new$z_axis) 

(你真的應該選擇比new的方式以外的其他名稱。)

然後,你可以子集的數據。但是,並通過調用scale_color_discrete使用drop=FALSE顯示在圖例中缺失的水平:

ggplot(data=new[new$Count!="2", ], aes(x_axis,y_axis, colour=Count), size=z_axis) +         
    geom_point(size=5) + 
    ggtitle("PB1-PB1") + 
    scale_colour_discrete(name="Counts", drop=FALSE) + 
    theme_bw() 

enter image description here

this question,其實。

+0

佩頓:看起來很完美的解決方案。 – Mdhale