2013-08-16 131 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