问题
I want to create a single legend for a bubble chart with positive and negative values like in plot below, generated using sp::bubble().
But, for various reasons I want to duplicate this in ggplot2. The closest I have gotten is to generate a single legend with scaled symbols, but the actual bubbles themselves are'nt scaled.
The above plot was created using the code below
# 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))))
回答1:
Continue using abs(value) for size and sign(value) for color.
Provide the breaks=
argument of scale_size_continuous()
with duplicates of breaks required (e.g. c(10,10,20,20,...)). Next, provide labels=
with the values you desire. Finally, use guides()
and override.aes
to set your own order of values and colours.
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))))
To assign exact values for the size=
argument in the guides()
function you could use function rescale()
from the scales
library. Rescale the entire range of values you are plotting, along with the break points provided to range=
argument in scale_size_continuous()
.
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
来源:https://stackoverflow.com/questions/40703656/r-ggplot2-creating-a-single-legend-in-a-bubble-chart-with-positive-and-negativ