在图中定制离散色标

Roy*_*lTS 1 r plotly

我想自定义plotly绘图中的颜色.这适用于连续变量和按照文档进行缩放:

library(plotly)

plot_ly(iris, x = Petal.Length, y = Petal.Width,
             color = Sepal.Length, colors = c("#132B43", "#56B1F7"),
             mode = "markers")
Run Code Online (Sandbox Code Playgroud)

但是,如果我将参数设置为离散颜色(字符或因子),这仍然有效,但会发出警告:

> plot_ly(iris, x = Petal.Length, y = Petal.Width,
          color = Sepal.Length>6, colors = c("#132B43", "#56B1F7"),
          mode = "markers")


Warning message:
In RColorBrewer::brewer.pal(N, "Set2") :
  minimal value for n is 3, returning requested palette with 3 different levels
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

Fel*_*lix 7

这不是一个阴谋问题,而是ColorBrewer(和相关RColorBrewer包)的设计特征.当您指定color等于或超过三个等级的因子时,您会注意到警告消失,例如

plot_ly(iris, x = Petal.Length, y = Petal.Width,
        color = cut(Sepal.Length, 3), colors = "Set1",
        mode = "markers")
Run Code Online (Sandbox Code Playgroud)

这是因为ColorBrewer的最小数据类数是三(您可以从http://colorbrewer2.org/看到,其中不能选择少于三个类).例如,在?brewer.pal(图中引用的函数)中,它具体说明了

所有顺序调色板都有3种不同值,最多9种不同值的变化.

[...]

对于定性调色板,可用的最小数量的不同值总是3

由于build_plotly()(plotly()内部函数调用)始终调用brewer.pal()(参见此处的第474行),因此如果不重写build_plotly()函数以便不brewer.pal()使用少于3个数据类调用,则无法修复此问题.

在此期间,要关闭警告,请将绘图输出分配给对象并将print(object)声明包装成suppressWarnings()如下所示:

plotly_plot <- plot_ly(iris, x = Petal.Length, y = Petal.Width,
      color = Sepal.Length>6, colors = c("#132B43", "#56B1F7"),
      mode = "markers")

suppressWarnings(print(plotly_plot))
Run Code Online (Sandbox Code Playgroud)