要获得背景,您可以使用它geom_raster
来获得您想要的效果。我将使用@GeekOnAcid 建议的相同数据集:
首先获取数据并拟合回归模型:
crime = read.csv("http://datasets.flowingdata.com/crimeRatesByState2005.tsv",
header=TRUE, sep="\t")
##Fit the regression model
m = lm(crime$burglary ~ crime$murder)
接下来我们为背景颜色创建一个网格:
##Create a grid for the background colour
x = seq(1, 10, length.out=100)
y = seq(400, 1200, length.out=100)
z = expand.grid(x,y)
现在我们需要一个渐变颜色的距离度量。我只是使用回归线的平方距离:
z$grad = (z[,2] - (398.3 + 62.2*z[,1]))^2
然后绘制:
require(ggplot2)
ggplot(z) + geom_raster(aes(Var1, Var2, fill=grad)) +
geom_point(data=crime[1:15,], aes(murder, burglary, size=population),pch=1 ) +
geom_text(data=crime[1:15,],
aes(murder, burglary, label=state),
hjust=-0.2, size=4) +
scale_size_continuous(range=c(1,10)) +
scale_fill_continuous(high="red", low="white", trans="sqrt") +
xlab("Murder") + ylab("Burglary") +
guides(size=FALSE, fill=FALSE) +
scale_y_continuous(expand=c(0, 0)) +
scale_x_continuous(expand=c(0, 0))
要得到: