自定义离散色标 [英] Custom discrete color scale in plotly
问题描述
我想自定义plotly
图中的颜色.对于文档:
I would like to customize the colors in a plotly
plot. This works fine for continuous variables and scales as per the 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
如何正确执行此操作?
推荐答案
这不是一个小问题,而是ColorBrewer(和关联的RColorBrewer
包)的设计功能.您会注意到,当您将color
分配给等于或大于三个级别的因素时,警告消失.
This isn't a plotly issue, but a design feature of ColorBrewer (and the associated RColorBrewer
package). You'll notice that the warning disappears when you assign color
to factors with equal to or more than three levels, e.g.
plot_ly(iris, x = Petal.Length, y = Petal.Width,
color = cut(Sepal.Length, 3), colors = "Set1",
mode = "markers")
这是因为ColorBrewer的数据类的最小数量为3(您可以从 http://colorbrewer2.org/不能选择少于三个类别).例如,在?brewer.pal
(plotly引用的函数)中,它具体说明了
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). For instance, in ?brewer.pal
(the function referenced by plotly), it specifically says
所有顺序调色板均提供3种版本 不同的值,最多9个不同的值.
All the sequential palettes are available in variations from 3 different values up to 9 different values.
[...]
对于定性调色板,可用的最少不同值始终为3
For qualitative palettes, the lowest number of distinct values available always is 3
由于build_plotly()
(内部调用函数plotly()
)始终会调用brewer.pal()
(请参见第474行此处),那么如果不重写build_plotly()
函数以不调用少于3个数据类的brewer.pal()
函数,则无法解决此问题.
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.
同时,要关闭警告,请将绘图输出分配给对象,然后将print(object)
语句包装在suppressWarnings()
中,如下所示:
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:
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))
这篇关于自定义离散色标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!