我具有用于通过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
作为标签以及图例名称和颜色的genus
和phylum
列来表示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))
这是我想要的图例:
任何线索?
如果我理解正确,您希望标签保持原样,并且only更改图例中显示的文本。如果是这样,可以通过以下方法轻松获得所需的内容:
我在图例中操作图例文本可以是tricky,因此,为了使内容尽可能简单,请不要使用图例,而是编辑标签。只需在piedat
中添加由phylum
和sunra
组成的另一列,将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