使用scale_size_area(ggplot2)将大小为“0”的点绘制为完全不存在

时间:2016-06-07 19:15:14

标签: r plot ggplot2

我正在尝试按群集制作条件的气泡图,其中每个气泡的大小由第三个“百分比”变量设置。作为per the ggplot2 documentation,我想我应该可以通过scale_size_area来做到这一点。我不清楚为什么这不起作用,当百分比= 0时我仍然看到非常小的点。 (如果我误解,我也很感激如何解决这个问题。在我的实际数据中,区分0和非常接近0非常重要。)

ex <- data.frame(Condition=rep(c("ex1","ex2","ex3","ex4"),4),
                 Cluster=c(rep(1,4),rep(2,4),rep(3,4),rep(4,4)),
             Percent=c(0,0,0,1,0.25,0,0.25,0.5,1,0,0,0,0.25,0.25,0.25,0.25))
ggplot(ex, aes(Cluster, Condition, size=Percent))+ 
           geom_point(color = "blue")+ scale_size_area(max_size=20)

example plot

2 个答案:

答案 0 :(得分:5)

尝试

library(ggplot2)
ex <- data.frame(Condition=rep(c("ex1","ex2","ex3","ex4"),4),
                 Cluster=c(rep(1,4),rep(2,4),rep(3,4),rep(4,4)),
             Percent=c(0,0,0,1,0.25,0,0.25,0.5,1,0,0,0,0.25,0.25,0.25,0.25))
ggplot(ex, aes(Cluster, Condition, size=ifelse(Percent==0, NA, Percent))))+ 
           geom_point(color = "blue")+ scale_size_area(max_size=20)

使用size=ifelse(Percent==0, NA, Percent))代替size=Percent将从绘图中排除这些点。

答案 1 :(得分:1)

您还可以使用data.table:

尝试以下操作
library(data.table)
ex2<-as.data.table(ex)
ggplot(ex2, aes(Cluster, Condition))+ 
geom_point(data=ex2[ex2$Percent > 0],aes(size=Percent), color = "blue")+scale_size_area(max_size=20)

在这里,您只需在geom_point中创建一个新框架,排除百分比等于0的所有行。 之前方法的问题是:如果所有行的百分比等于零,请说

Percent=c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)

您将收到错误

  

grid.Call.graphics(C_setviewport,vp,TRUE)中的错误:     nicht-endlicher Ort oder /undGrößedesViewports

如果你使用数据表方法(或任何其他方法,只给你ggplot你想要绘制的信息),你没有任何问题,你只会得到一个空的情节,如果是自动脚本比崩溃更好。