gpt4 book ai didi

r - 绘图中的自定义离散色阶

转载 作者:行者123 更新时间:2023-12-02 14:23:47 24 4
gpt4 key购买 nike

我想自定义 plotly 图中的颜色。这对于连续变量和尺度来说效果很好,如 docs 所示。 :

library(plotly)

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

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

> 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

如何正确执行此操作?

最佳答案

这不是一个 plotly 问题,而是 ColorBrewer(以及相关的 RColorBrewer 包)的设计功能。您会注意到,当您将颜色分配给等于或超过三个级别的因素时,警告消失了,例如

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

这是因为 ColorBrewer 的数据类的最小数量为 3(您可以从 http://colorbrewer2.org/ 中看到,其中不能选择少于 3 个类)。例如,在 ?brewer.pal (plotly引用的函数)中,它特别指出

All the sequential palettes are available in variations from 3 different values up to 9 different values.

[...]

For qualitative palettes, the lowest number of distinct values available always is 3

由于 build_plotly() (函数 plotly() 内部调用)总是调用 brewer.pal() (参见第 474 行 here ) ,如果不重写 build_plotly() 函数以不调用少于 3 个数据类的 brewer.pal() ,则无法解决此问题。

同时,要关闭警告,请将绘图输出分配给一个对象,并将 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))

关于r - 绘图中的自定义离散色阶,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38740837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com