gpt4 book ai didi

R,ggplot2 : creating a single legend in a bubble chart with positive and negative values

转载 作者:行者123 更新时间:2023-12-01 23:40:52 25 4
gpt4 key购买 nike

我想为具有正值和负值的气泡图创建单个图例,如 plot below 中所示,使用 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(value),对颜色使用 sign(value)。

scale_size_continuous()breaks= 参数提供所需中断的副本(例如 c(10,10,20,20,...))。接下来,为 labels= 提供您想要的值。最后,使用 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= 参数分配精确值,您可以使用 中的函数 rescale() >缩放库。重新缩放您正在绘制的整个值范围,以及提供给 scale_size_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

关于R,ggplot2 : creating a single legend in a bubble chart with positive and negative values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40703656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com