简体   繁体   English

自定义离散色标

[英]Custom discrete color scale in plotly

I would like to customize the colors in a plotly plot. 我想自定义的颜色在plotly情节。 This works fine for continuous variables and scales as per the docs : 对于连续变量和按docs的比例来说,这很好用:

library(plotly)

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

If I make the argument to color discrete (character or factor), however, this still works but throws a warning: 但是,如果我将参数设为颜色离散(字符或因数),则此方法仍然有效,但会发出警告:

> 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

How do I do this correctly? 如何正确执行此操作?

This isn't a plotly issue, but a design feature of ColorBrewer (and the associated RColorBrewer package). 这不是一个小问题,而是ColorBrewer(以及相关的RColorBrewer软件包)的设计功能。 You'll notice that the warning disappears when you assign color to factors with equal to or more than three levels, eg 您会注意到,当您将color分配给等于或大于三个级别的因子时,警告会消失,例如

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

This is because ColorBrewer's minimum number of data classes is three (which you can see from http://colorbrewer2.org/ where can't select fewer than three classes). 这是因为ColorBrewer的数据类别的最小数量是三个(您可以从http://colorbrewer2.org/看到,在其中不能选择少于三个类别)。 For instance, in ?brewer.pal (the function referenced by plotly), it specifically says 例如,在?brewer.pal (由plotly引用的函数)中,它具体说

All the sequential palettes are available in variations from 3 different values up to 9 different values. 所有顺序调色板都可以从3个不同的值到9个不同的值进行变化。

[...] [...]

For qualitative palettes, the lowest number of distinct values available always is 3 对于定性调色板,可用的最少不同值始终为3

Since build_plotly() (the function plotly() calls internally) always calls brewer.pal() (see line 474 here ), it's not possible to fix this without rewriting the build_plotly() function to not call brewer.pal() with fewer than 3 data classes. 由于build_plotly() (内部调用函数plotly() )始终调用brewer.pal() (请参见此处的第474行),因此如果不重写build_plotly()函数而不用更少的调用brewer.pal()来解决此问题是不可能的。超过3个数据类。

In the meantime, to turn off the warning, assign the plot output to an object and wrap the print(object) statement in suppressWarnings() like this: 同时,要关闭警告,请将绘图输出分配给一个对象,然后将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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM