具有不同列的R plot_ly饼图图例

问题描述 投票:1回答:1

我具有用于通过plot_ly()函数建立饼图的数据框:

piedat <- data.frame("phylum" = c("Non-classified genera", "Genera with RA < 1%", "Firmicutes", "Fibrobacteres", "Bacteroidetes", "Bacteroidetes"),
                     "genus" = c("Unclassified", "RA < 1%", "Clostridium", "Fibrobacter", "Bacteroides", "Prevotella"),
                     "sunra" = c(51.123358, 24.086378, 1.798356, 2.405086, 1.115162, 19.471660),
                     "col" = c("#F8766D", "#A3A500", "#00BF7D", "#00B0F6", "#E76BF3", "#E76BF3"))

我希望饼图使用sunra作为颜色,col作为标签以及图例名称和颜色的genusphylum列来表示col丰度(它们的总和为100),分别。使用此代码,我几乎可以完成所有操作,因为图例仍然保留genus名称:

pie <- plot_ly(piedat) %>%
  add_trace(labels = ~genus, values = ~sunra, name = "phylum", type = 'pie', textposition = 'auto', sort = F, 
            textinfo = 'label+percent', textfont = list(size = 14), marker = list(line = list(width = 1))) %>% 
  layout(autosize = T, showlegend = T, colorway = piedat$col,
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

enter image description here

这是我想要的图例:

enter image description here

任何线索?

r plotly legend pie-chart
1个回答
0
投票

如果我理解正确,您希望标签保持原样,并且only更改图例中显示的文本。如果是这样,可以通过以下方法轻松获得所需的内容:


我在图例中操作图例文本可以是tricky,因此,为了使内容尽可能简单,请不要使用图例,而是编辑标签。只需在piedat中添加由phylumsunra组成的另一列,将labels = ~genus更改为labels = ~phylum,将textinfo = 'label+percent'更改为textinfo = 'text'并在text=~custom中包含add_trace()即可:

enter image description here

完整代码:

piedat <- data.frame("phylum" = c("Non-classified genera", "Genera with RA < 1%", "Firmicutes", "Fibrobacteres", "Bacteroidetes", "Bacteroidetes"),
                     "genus" = c("Unclassified", "RA < 1%", "Clostridium", "Fibrobacter", "Bacteroides", "Prevotella"),
                     "sunra" = c(51.123358, 24.086378, 1.798356, 2.405086, 1.115162, 19.471660),
                     "col" = c("#F8766D", "#A3A500", "#00BF7D", "#00B0F6", "#E76BF3", "#E76BF3"))

piedat$custom <- paste(piedat$genus, format(piedat$sunra, digits=2))

pie <- plot_ly(piedat) %>%
  add_trace(labels = ~phylum, values = ~sunra, name = "phylum", type = 'pie', textposition = 'auto', sort = F, 
            textinfo = 'text', text=~custom, textfont = list(size = 14), marker = list(line = list(width = 1))) %>% 
  layout(autosize = T, showlegend = T, colorway = piedat$col,
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

pie
© www.soinside.com 2019 - 2024. All rights reserved.