【问题标题】:PlotlyR - Scatter LegendPlotly - 散点图例
【发布时间】:2021-08-10 22:21:34
【问题描述】:

我正在尝试基于 3 个级别在 R 中显示一个图例。

cols <- c(Poor = "steelblue",
          Fair = "slateblue",
          Good = "grey45")

我已阅读多个条目,说明该列必须是类因子。即使使用这种变异“showlegend = T”也不会显示图例。是否可以在不单独添加所有 3 个标记的情况下执行此操作?


plot_data <- plot_data %>% mutate(label_col = as.factor(label_col))
        
        p <-   plot_ly(data = plot_data,
                       x = ~r_score,
                       y = ~b_score,
                       type = "scatter",
                       marker = list( title = "Rating",
                                      size = ~plot_data$TTM_Units ,
                                      color = ~cols[plot_data$label_col],
                                      line = list(color = 'rgba(1, 0, 0, .8)',
                                                  width = 2),
                                      opacity = .5),
                                      showlegend = TRUE,
                                      inherit = TRUE)

【问题讨论】:

    标签: r r-plotly


    【解决方案1】:

    您可以通过在color 属性上映射一个变量并通过颜色参数设置您想要的调色板来实现您想要的结果。

    使用ggplot2::diamonds 数据集作为示例数据:

    cols <- c(
      Poor = "steelblue",
      Fair = "slateblue",
      Good = "grey45"
    )
    
    library(plotly)
    
    plot_data <- diamonds %>%
      filter(cut %in% names(cols))
    
    plot_ly(
      data = plot_data,
      x = ~carat,
      y = ~price,
      color = ~cut,
      size = ~depth,
      type = "scatter",
      mode = "markers",
      colors = cols,
      marker = list(
        title = "Rating",
        line = list(
          color = "rgba(1, 0, 0, .8)",
          width = 2
        ),
        opacity = .5
      )
    )
    #> Warning: `line.width` does not currently support multiple values.
    
    #> Warning: `line.width` does not currently support multiple values.
    

    【讨论】:

      猜你喜欢
      • 2021-11-04
      • 2017-01-17
      • 2020-07-27
      • 2020-05-15
      • 1970-01-01
      • 2021-05-11
      • 2022-01-16
      • 2020-09-04
      • 2022-01-21
      相关资源
      最近更新 更多