簡體   English   中英

在圖解圖例中分隔符號和顏色

[英]Separate symbol and color in plotly legend

我希望通過plotly獲得與此ggplot代碼相同的結果:

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

這導致: 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')

它列舉了圖例中顏色和形狀的所有可能組合。 在此輸入圖像描述

有沒有辦法讓ggplot有類似的傳說?

更新 :為了克服我之前的解決方案中提到的一些問題(見下文)並增加圖例的可用性,可以簡單地將列名添加到圖例描述中,然后將圖例組分配給每個類別。

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等價物:

基於此線程中dww的答案,我們可以手動創建cylindersgears 隨后,通過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")) 

未解決的問題:

  • 必須手動創建組
  • 組剛剛重疊(顏色超過形狀)。 這意味着只能在圖例中禁用/激活整個組(例如,不能僅顯示具有4個柱面的條目)
  • 第二個圖例標題(注釋)的位置取決於圖的高度!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM