ggplot:使用scale_fill_gradient获取离散图例

bal*_*n16 5 gradient r legend ggplot2

我正在尝试重新创建“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)) 
Run Code Online (Sandbox Code Playgroud)

这使

在此输入图像描述

bal*_*n16 6

问题解决了。事实证明我必须添加指导参数:

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") 
Run Code Online (Sandbox Code Playgroud)