在图解图例中分隔符号和颜色

jav*_*vad 6 r data-visualization plotly

我希望通过plotly获得与此ggplot代码相同的结果:

mtcars %>% add_rownames('car') %>% 
ggplot(aes(x = mpg,
         y = disp,
         color = as.factor(gear),
         shape = as.factor(cyl))) +
geom_point()
Run Code Online (Sandbox Code Playgroud)

这导致: ggplot版本

我的情节代码是:

library(dplyr)
mtcars %>% add_rownames('car') %>% 
plot_ly(x = ~mpg, 
      y = ~disp,
      text = ~car,
      color = ~as.factor(gear),
      symbol = ~as.factor(cyl),
      mode = 'markers')
Run Code Online (Sandbox Code Playgroud)

它列举了图例中颜色和形状的所有可能组合. 在此输入图像描述

有没有办法让ggplot有类似的传说?

Nin*_*ino 6

更新:为了克服我之前的解决方案中提到的一些问题(见下文)并提高图例的可用性,可以简单地将列名称添加到图例描述中,然后将图例组分配给每个类别。

mtcars %>% rownames_to_column('car') %>%
    plot_ly() %>%
    #Plot symbols for cyl
    add_trace(type = "scatter",
              x = ~mpg, 
              y = ~disp,
              text = ~car,
              symbol = ~paste0(cyl," cyl."),
              mode = 'markers',
              marker = list(color = "grey", size = 15)) %>%
    #Overlay color for gears
    add_trace(type = "scatter",
              x = ~mpg, 
              y = ~disp,
              text = ~car,
              color = ~paste0(gear, " gears"),
              mode = 'markers')
Run Code Online (Sandbox Code Playgroud)


这是之前的解决方案,在视觉上更接近 ggplot2 等效项:

根据 dww 在此线程中的回答,我们可以手动为cylinders和创建组gears。随后,通过 Artem Sokolov这个线程的回答,我们可以添加图例标题作为注释。

mtcars %>% rownames_to_column('car') %>% 
  plot_ly() %>%
  #Plot symbols for cyl
  add_trace(type = "scatter",
            x = ~mpg, 
            y = ~disp,
            text = ~car,
            symbol = ~as.factor(cyl),
            mode = 'markers',  
            legendgroup="cyl",
            marker = list(color = "grey", size = 15)) %>%
  #Overlay color for gears
  add_trace(type = "scatter",
            x = ~mpg, 
            y = ~disp,
            text = ~car,
            color = ~as.factor(gear),
            mode = 'markers', 
            legendgroup="gear") %>%
  #Add Legend Titles (manual)
  add_annotations( text="Cylinders:", xref="paper", yref="paper",
                   x=1.02, xanchor="left",
                   y=0.9, yanchor="bottom",    # Same y as legend below
                   legendtitle=TRUE, showarrow=FALSE ) %>%

  add_annotations( text="Gears:", xref="paper", yref="paper",
                   x=1.02, xanchor="left",
                   y=0.7, yanchor="bottom",    # Y depends on the height of the plot
                   legendtitle=TRUE, showarrow=FALSE ) %>%

  #Increase distance between groups in Legend
  layout(legend=list(tracegroupgap =30, y=0.9, yanchor="top")) 
Run Code Online (Sandbox Code Playgroud)

未解决的问题:

  • 必须手动创建组
  • 组只是重叠(颜色超过形状)。这意味着只能在图例中禁用/激活整个组(例如,不可能仅显示具有 4 个气缸的条目)
  • 第二个图例标题(注释)的位置取决于情节的高度!