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

use*_*581 6 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()
Run Code Online (Sandbox Code Playgroud)

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

苏菲亚

Did*_*rts 14

一种可能性是使用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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在此输入图像描述

UPDATE

正如@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))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 在此输入图像描述