ggplot:使用 scale_fill_gradient 获取离散图例

ggplot: get discrete legend with scale_fill_gradient

我正在尝试重新创建 'R Graphics Cookbook' 第 87 页的示例图。

我正在尝试使用以下代码重新创建,但没有得到结果:

library(ggplot2)
library(hexbin)

sp <- ggplot(diamonds, aes(x=carat, y=price))
sp + stat_binhex() +
  scale_fill_gradient(low="lightblue", high="red",
                      breaks=c(0, 250, 500, 1000, 2000, 4000, 6000),
                      limits=c(0, 6000)) 

这给出了

问题已解决。结果我不得不添加指南参数:

sp <- ggplot(diamonds, aes(x=carat, y=price))
    sp + stat_binhex() +
      scale_fill_gradient(low="lightblue", high="red",
                          breaks=c(0, 250, 500, 1000, 2000, 4000, 6000),
                          limits=c(0, 6000), guide = "legend")