R、 ggplot2:在气泡图中创建具有正值和负值的单个图例

R、 ggplot2:在气泡图中创建具有正值和负值的单个图例,r,plot,ggplot2,legend,bubble-chart,R,Plot,Ggplot2,Legend,Bubble Chart,我想为气泡图创建一个图例,其中包含正数和负值,如使用sp::bubble()生成的绘图中的值 但是,出于各种原因,我想在ggplot2中复制这一点。我得到的最接近的结果是生成一个带有缩放符号的图例,但实际的气泡本身并没有缩放 上面的图是使用下面的代码创建的 # create data frame x=sample(seq(1,50),50,T) y=sample(seq(1,50),50,T) plot_dat=data.frame(x=x,y=y,value=rnorm(50,0,25))

我想为气泡图创建一个图例,其中包含正数和负值,如使用sp::bubble()生成的绘图中的值

但是,出于各种原因,我想在ggplot2中复制这一点。我得到的最接近的结果是生成一个带有缩放符号的图例,但实际的气泡本身并没有缩放

上面的图是使用下面的代码创建的

# create data frame
x=sample(seq(1,50),50,T)
y=sample(seq(1,50),50,T)
plot_dat=data.frame(x=x,y=y,value=rnorm(50,0,25))

# plot
library(ggplot2)
ggplot(data=plot_dat, aes(x=x, y=y,colour=factor(sign(value)), size=value)) +
geom_point() +  
scale_size(breaks = c(-40,-30,-20,-10,0,10,20,30,40,50), range = c(0.5,4)) +
scale_colour_manual(values = c("orange", "blue"), guide=F) +
guides(size = guide_legend(override.aes = list(colour = list("orange","orange","orange","orange","blue","blue","blue","blue","blue","blue"),size=c(3,2.5,2,1,0.5,1,2,2.5,3,4)))) 
继续使用abs(值)表示尺寸,符号(值)表示颜色

提供
scale\u size\u continuous()
breaks=
参数,需要重复的中断(例如c(10,10,20,20,…)。接下来,为标签提供所需的值。最后,使用
guides()
override.aes
设置您自己的值和颜色顺序

ggplot(data=plot_dat, aes(x=x, y=y,colour=factor(sign(value)), size=abs(value))) +
      geom_point() +
      scale_color_manual(values=c("orange","blue"),guide=FALSE)+
      scale_size_continuous(breaks=c(10,10,20,20,30,30,40,40,50,50),labels=c(-50,-40,-30,-20,-10,10,20,30,40,50),range = c(1,5))+
      guides(size = guide_legend(override.aes = list(colour = list("orange","orange","orange","orange","orange","blue","blue","blue","blue","blue"),
                                               size=c(4.92,4.14,3.50,2.56,1.78,1.78,2.56,3.50,4.14,4.92))))
要为
guides()
函数中的
size=
参数指定精确值,可以使用
scales
库中的函数
rescale()
。重新缩放正在打印的整个值范围,以及
scale\u size\u continuous()
中提供给
range=
参数的断点


谢谢迪兹!重缩放功能是一个很好的补充。
set.seed(1234)
x=sample(seq(1,50),50,T)
y=sample(seq(1,50),50,T)
plot_dat=data.frame(x=x,y=y,value=rnorm(50,0,20))

library(scales)
rescale(c(abs(plot_dat$value),10,20,30,40,50),to=c(1,5))[51:55]
[1] 1.775906 2.562657 3.349409 4.136161 4.922912