ggplot2中各点的大小可以比较?

时间:2013-04-22 09:36:10

标签: r ggplot2

我正在使用ggplot2来生成各种图,其中点的大小与具有相同x和y值的个案的数量成比例。有没有办法在具有不同size值的不同图中使点的大小具有可比性?

使用虚假数据的示例:

    df1 = data.frame(x = seq(1:10), 
            y = c(4,3.8,3.8,3.2,3.1,2.5,2,1.5,1.2,1.3),
            size = c(1,20,1,70,100,70,1,1,110,1))

    library(ggplot2)

    pdf("plot.1.pdf")
    ggplot(df1, aes(x = x, y = y, size = size)) + geom_point()
    dev.off()

    df2 = data.frame(x = seq(1:10), 
            y = c(4,3.8,3.8,3.2,3.1,2.5,2,1.5,1.2,1.3),
            size = rep(1,length(y)))
    pdf("plot.2.pdf")
    ggplot(df2, aes(x = x, y = y, size = size)) + geom_point()
    dev.off()

Plot 1中的size等于1的点远远大于P size等于1的点。我需要一个版本的点,其中点与相同的size值在不同的图中具有相同的大小。谢谢,

索菲亚

1 个答案:

答案 0 :(得分:13)

一种可能性是使用scale_size_identity() - 将size直接解释为pointsize的单位,因此在两个图中,值为1的点将具有相同的大小。但是如果size值很大(如你的情况那样),这种方法会产生太大的分数。要处理太大点的问题,可以使用变量内部的变换,例如平方根,使用参数trans="sqrt"

ggplot(df1, aes(x = x, y = y, size = size)) + 
  geom_point()+scale_size_identity(trans="sqrt",guide="legend")

ggplot(df2, aes(x = x, y = y, size = size)) + 
  geom_point()+scale_size_identity(trans="sqrt",guide="legend")

enter image description here

enter image description here

更新

正如@hadley所指出的,最简单的方法是将limits=内的scale_size_continuous()设置为相同的值以获得相同的大小。

ggplot(df1, aes(x = x, y = y, size = size)) + geom_point()+
  scale_size_continuous(limits=c(1,110))
ggplot(df2, aes(x = x, y = y, size = size)) + geom_point()+
  scale_size_continuous(limits=c(1,110))

enter image description here enter image description here