首页 > 解决方案 > R绘图表的条件格式

问题描述

我想有条件地格式化表格中的行。如果一列有 1,则该列应突出显示,否则不突出显示。我想在情节中做到这一点。数据如下:

Name Purchased
a    0
b    1
c    0
d    1

我想突出显示名称为 b 和 d 的行。

我正在使用以下类型的代码:

plot_ly(
          type = 'table',
          columnwidth = c(100, 100, 100),
          columnorder = c(0, 1, 2),
          header = list(
            values =  c(A,B),
            align = c("center", "center"),
            line = list(width = 1, color = 'black'),
            fill = list(color = c("grey", "grey")),
            font = list(family = "Arial", size = 14, color = "white")
          ),
          cells = list(
            values = rbind(df[[A]],df[[B]]),
            align = c("center", "center"),
            line = list(color = "black", width = 1),
            font = list(family = "Arial", size = 12, color = c("black"))
          ))

我正在为 R 闪亮的应用程序编写此代码。请让我知道我该怎么做。

标签: rshinyconditional-formattingr-plotly

解决方案


我会highlight在原始数据集中为必须突出显示的每一行添加一个变量。

df <- df %>% 
  mutate(highlgt = ifelse(Purchased == 1, "lightblue", "white"))

然后,在cells参数中,使用fill值列表更新highlight值。
(我还更改了header/valuesandcells/values值以避免错误消息)。

plot_ly(
  type = 'table',
  columnwidth = c(100, 100),
  #columnorder = c(0, 1, 2),
  header = list(
    values =  c("A","B"),
    align = c("center", "center"),
    line = list(width = 1, color = 'black'),
    fill = list(color = c("grey", "grey")),
    font = list(family = "Arial", size = 14, color = "white")
  ),
  cells = list(
    values = rbind(df[[1]], df[[2]]),
    align = c("center", "center"),
    line = list(color = "black", width = 1),
    font = list(family = "Arial", size = 12, color = c("black")),
    fill = list(color = list(df$highlgt))   # highlight rows
  ))

plotly_table_highlight_rows


推荐阅读