问题
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 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, 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