2016-11-20 109 views
3

我想爲具有正值和負值的氣泡圖創建單個圖例,如使用sp :: bubble()生成的圖below中的圖例。R,ggplot2:在帶有正值和負值的氣泡圖中創建單個圖例

但是,由於種種原因,我想在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)))) 

回答

3

代碼繼續使用大小和顏色符號(值)ABS(值)創建的。

提供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()scales庫指定精確值。重新縮放您正在繪製的整個值範圍,以及在中爲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 

+0

感謝Didzis!重新調整功能是一個很好的補充。 – zoneparser