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

z5btuh9x  于 2022-12-20  发布在  其他
关注(0)|答案(2)|浏览(181)

我有这个数据框,用于构建一个饼图与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"))

我希望饼图使用col作为颜色,genus作为标签,phylumcol列分别作为图例名称和颜色来表示sunra丰度(它们的总和为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))

这就是我想要的传奇

有线索吗?

ccrfmcuu

ccrfmcuu1#

如果我没理解错的话,您可能希望标签保持原样,并且***只***更改图例中显示的文本。如果是这种情况,下面是您可以轻松获得所需内容的方法:
绘图操作图例文本i可以是tricky,因此为了使事情尽可能简单,请保留图例,改为编辑标签。只需向piedat添加另一列(由phylumsunra组成),将labels = ~genus更改为labels = ~phylum,将textinfo = 'label+percent'更改为textinfo = 'text',并将text=~custom包含在add_trace()中即可获得:

完整代码:

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
vktxenjb

vktxenjb2#

一个非图形化的解决方案是将变量的水平更改为您希望它们出现的顺序。

piedata$phylum <- factor(piedata$phylum, levels=c("Non-classified genera", "Genera with RA < 1%", "Firmicutes", "Fibrobacteres", "Bacteroidetes")

相关问题