Hide labels in plotly donut chart r

◇◆丶佛笑我妖孽 提交于 2021-02-10 14:14:50

问题


I am working on a Shiny app where I am plotting a Donut chart. The slices depend on the variable selected and sometimes are too small. In such cases the labels are displayed outside the chart like in the image below.

Is there a way to altogether hide all the labels (values with % sign) in the chart and only allow the hover action to show the details?

An reproducible code for a Donut Chart is as below:

library(plotly)
library(tidyr)
library(dplyr)
# Get Manufacturer
mtcars$manuf <- sapply(strsplit(rownames(mtcars), " "), "[[", 1)

p <- mtcars %>%
  group_by(manuf) %>%
  summarize(count = n()) %>%
  plot_ly(labels = ~manuf, values = ~count) %>%
  add_pie(hole = 0.6) %>%
  layout(title = "Donut charts using Plotly",  showlegend = F,
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

p

回答1:


You could set textinfo='none' to get the following donut plot which has no text in the pie elements but shows info on hovering.




回答2:


You can control what is shown in a plotly pie chart using the textinfo and hoverinfoattributes. One solution to your problem would be setting the textinfo = "none" and hoverinfo = "text" while specifying that text = ~manuf as in:

library(plotly)
library(tidyr)
library(dplyr)
# Get Manufacturer
mtcars$manuf <- sapply(strsplit(rownames(mtcars), " "), "[[", 1)

p <- mtcars %>%
  group_by(manuf) %>%
  summarize(count = n()) %>%
  plot_ly(text = ~manuf, values = ~count, textinfo = "none", hoverinfo = "text") %>%
  add_pie(hole = 0.6) %>%
  layout(title = "Donut charts using Plotly",  showlegend = F,
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

p

You can further customize the text that is shown on hover by pasting any combination of strings with <br> seperators, e.g.:

plot_ly(text = ~paste("Manuf.: ", manuf , "<br> Number: ", count) , values = ~count, textinfo = "none", hoverinfo = "text") %>%



来源:https://stackoverflow.com/questions/42822924/hide-labels-in-plotly-donut-chart-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!