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

时间:2017-11-28 19:34:40

标签: 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()

导致: ggplot version

我的情节代码是:

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

枚举图例中颜色和形状的所有可能组合。 enter image description here

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

1 个答案:

答案 0 :(得分:3)

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

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')

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

根据this thread中dww的回答,我们可以手动为cylindersgears创建群组。随后,通过Artem Sokolov this thread的答案,我们可以添加图例标题作为注释。

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")) 

未解决的问题:

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