简体   繁体   中英

Hide labels in plotly donut chart r

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

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

在此输入图像描述

You can control what is shown in a plotly pie chart using the textinfo and hoverinfo attributes. 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, eg:

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

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM