R剧情:分割图例:符号和颜色

时间:2018-08-22 10:50:16

标签: r plotly legend

对于每个数据点“符号”和“名称”,我都有一些数据和两个类别。我正在绘制数据并使用不同的符号和颜色映射类别,如下所示。

data <- data.frame(
        x= c(1,2,3,4,5,6,7,8),
        y = c(10,11,10,12,11,9,8,13), 
        symbol = c("invalid", "valid", "invalid",
                   "valid", "valid", "valid","valid", "valid"),
        name = c("A", "B", "B", "A", "A", "A", "B", "B"))


plot_ly(data) %>%
add_markers(y = ~y,  x = ~x,  symbol = ~symbol, color = ~name,
            symbols = c(4, 27),
            mode = 'markers',
            #split = ~name,
            colors = c("red", "navy"))

enter image description here

传说很笨拙。

我想将两个图例条目与十字架合并,并在图例中为十字架添加中性色,如下所示:

enter image description here

我尝试使用split参数,但这没有帮助。

1 个答案:

答案 0 :(得分:1)

您可以通过3个步骤进行操作:

  1. 绘制有效数据
  2. 将所有无效数据绘制为灰色并带有图例
  3. 以无图例的颜色过度绘制所有无效数据

代码:

data$labels <- data$name
levels(data$labels) <- c("A", "B", "invalid")

plot_ly(data, colors = c("red", "navy", "grey")) %>%
  add_markers(y = ~y,  x = ~x, color = ~labels,
              data = data[data$symbol == "valid",],
              symbols = 4,
              mode = 'markers') %>%
  add_markers(y = ~y,  x = ~x,  symbol = ~symbol, 
              color = factor("invalid", levels = c("A", "B", "invalid")),
              data = data[data$symbol == "invalid",],
              symbols = 27,
              mode = 'markers',
              name = 'invalid',
              legendgroup = factor("invalid", levels = c("A", "B", "invalid"))) %>%
  add_markers(y = ~y,  x = ~x,  symbol = ~symbol, color = ~labels,
              data = data[data$symbol == "invalid",],
              symbols = 27,
              mode = 'markers',
              legendgroup = factor("invalid", levels = c("A", "B", "invalid")),
              showlegend = FALSE)

结果:

enter image description here