[英]How to set discrete Colors in Plotly R Barplot
我正在尝试使用 R 中的 Plotly 在 Shiny 应用程序中复制条形图(见下图)。 x 轴具有组织值,而 x 轴上的每个条根据组织细节拆分/堆叠。 当我尝试复制上图时,对于某些组织值,我无法使用预定义的 plotly 色标(参见下面的“大脑”和“心脏”)来离散区分组织细节,这些条基本上具有相同颜色的变化家庭,使他们难以解释。
是否有可能以某种方式生成一个 colors 的图形,就像我想在 plotly R 中复制的那样? 动态地? 由于组织的组织详细信息可能会根据 shiny select 输入选择而改变。
这是我的 plotly function:
plot_ly(data = tissue_dt, y=~counts, x=tissue, type='bar', name=~tissue_detail, color=~tissue_detail, colors = "Paired") %>% layout(barmode ="stack")
除此之外,我还尝试了“Set3”和所有其他 plotly 离散色阶,但没有成功。
用于所需 plot 和 shiny plot 的数据是相同的
请注意,原始 plot 为每个组织/细节使用了离散颜色。
如果 tissue_detail 的列表是固定的,最好的选择是使用手动调色板,例如:
my.pal = {
"Adipose-subcutaneous" = "#a10335", #Or whatever color you want
"Adipose-visceral" = "#43a332",
"AdrenalGland" = "green2",
# AND the remaining categories. The labels should match those in tissue_detail
}
只需在您的 plot 中使用该调色板
plot_ly(data = tissue_dt, y=~counts, x=tissue, type='bar', name=~tissue_detail, color=~tissue_detail, colors = my.pal) %>% layout(barmode ="stack")
如果您在其他图中部分使用这些数据,这还有一个额外的优势。 因此,您可以保留对每个 tissue_detail 的 colors 的分配,即使这些图中的任何一个都缺少一些类别。
有这么多(子)类别,定义一个有意义的离散调色板将相当困难。 但是,借助plotly's
hover 功能并在条形图周围添加一条(白)线,您应该会得到一个相当不错的图表:
library(dplyr)
library(tibble)
library(plotly)
library(RColorBrewer)
tissues <- tibble(tissue = LETTERS)
set.seed(18012023)
tissue_dt <- tissues %>%
slice(rep(sample(26, 8), sample(14, 8, TRUE))) %>%
mutate(tissue_detail = paste(tissue, sample(letters, n(), TRUE))) %>%
right_join(tissues, "tissue") %>%
mutate(tissue_detail = coalesce(tissue_detail, tissue),
counts = rpois(n(), 200)) %>%
arrange(tissue)
plot_ly(data = tissue_dt, y = ~counts, x = ~ tissue,
type = "bar",
name = ~tissue_detail,
marker = list(line = list(color = "white",
width = 1.5)),
color = ~tissue_detail,
colors = ~ tissue_detail %>%
as.factor() %>%
nlevels() %>%
colorRampPalette(brewer.pal(9, "Set1"))(.)) %>%
layout(barmode ="stack")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.