这是动态调整 binwidth 的解决方案。我已经包括处理纵向纵横比和明确规定的轴限制。
bins <- function(xMin,xMax,yMin,yMax,height,width,minBins) {
if(width > height) {
hbins = ((width/height)*minBins)
vbins = minBins
} else if (width < height) {
vbins = ((height/width)*minBins)
hbins = minBins
} else {
vbins = hbins = minBins
}
binwidths <- c(((xMax-xMin)/hbins),((yMax-yMin)/vbins))
return(binwidths)
}
例如这段代码:
h = 5
w = 5
yMin = min(diamonds$price)
yMax = max(diamonds$price)
xMin = min(diamonds$carat)
xMax = max(diamonds$carat)
minBins = 30
d <- ggplot(diamonds, aes(x = carat, y = price))+
stat_binhex(colour="white", binwidth = bins(xMin,xMax,yMin,yMax,h,w,minBins))+
ylim(yMin,yMax)+
xlim(xMin,xMax)
try(ggsave(plot=d,filename=<some file>,height=h,width=w))
产量:
当我们改变宽度时:
w = 8
d <- ggplot(diamonds, aes(x = carat, y = price))+
stat_binhex(colour="white", binwidth = bins(xMin,xMax,yMin,yMax,h,w,minBins))+
ylim(yMin,yMax)+
xlim(xMin,xMax)
try(ggsave(plot=d,filename=<some file>,height=h,width=w))
或者改变高度:
h = 8
w = 5
d <- ggplot(diamonds, aes(x = carat, y = price))+
stat_binhex(colour="white", binwidth = bins(xMin,xMax,yMin,yMax,h,w,minBins))+
ylim(yMin,yMax)+
xlim(xMin,xMax)
try(ggsave(plot=d,filename=<some file>,height=h,width=w))
我们还可以更改 x 和 y 限制:
h = 5
w = 5
xMin = -2
d <- ggplot(diamonds, aes(x = carat, y = price))+
stat_binhex(colour="white", binwidth = bins(xMin,xMax,yMin,yMax,h,w,minBins))+
ylim(yMin,yMax)+
xlim(xMin,xMax)
try(ggsave(plot=d,filename=<some file>,height=h,width=w))